Registry / serialization / typescript-memoize

typescript-memoize

JSON →
library1.1.1jsnpmunverified

typescript-memoize is a decorator library for TypeScript that enables method and getter memoization, primarily for optimizing performance by caching the results of expensive operations. As of version 1.1.1, it provides `@Memoize` for standard caching and `@MemoizeExpiring` for time-limited caching, which automatically invalidates cached values after a specified duration. The library offers flexibility in how memoization keys are generated, supporting methods without parameters, `get` accessors, and methods where memoization is based on specific parameters or custom hash functions. It's a stable library, though release cadence is not explicitly defined, new versions appear infrequently. Its key differentiator lies in its decorator-based approach, integrating seamlessly with TypeScript classes, and allowing for granular control over cache invalidation via custom hash functions or expiration.

npm install typescript-memoize
INSTALL
IMPORT
SIG · TYPESCRIPT-MEMOIZE
T
typescript-memoize
serializationjavascriptv1.1.1
Install
Import
Disk
Pass rate
0/ 6
Env Coverage0 / 6
glibc
1822
musl
1822
Install & Compatibility
Where this runs
tested against v? · npm install
Install × environment matrix
Each cell = how many times install + import succeeded across repeated harness runs. Partial = flaky.
glibc = Debian/Ubuntu slim · musl = Alpine Linux
musl
node 18226 runs
build_error
glibc
node 18226 runs
build_error
Code
Verified usage

Verified import paths — ran on the pinned version, not inferred.

Memoize
import { Memoize } from 'typescript-memoize';
const Memoize = require('typescript-memoize');
The primary decorator for caching method or getter results. Requires 'experimentalDecorators' and 'emitDecoratorMetadata' in tsconfig.json.
MemoizeExpiring
import { MemoizeExpiring } from 'typescript-memoize';
import MemoizeExpiring from 'typescript-memoize';
Used for caching with automatic invalidation after a specified time in milliseconds.
Custom Hash Function
@Memoize((param1: any, param2: any) => `${param1}-${param2}`)
Pass a function to `@Memoize` to define how cache keys are generated from method arguments, useful for complex parameter types or multi-parameter methods.

Demonstrates basic `@Memoize`, `@MemoizeExpiring` with a time limit, and `@Memoize` with a custom hash function for complex parameters, showing cache hits and expirations in a class context.

import { Memoize, MemoizeExpiring } from 'typescript-memoize'; class DataService { private callCount: number = 0; @Memoize() public getExpensiveData(): string { this.callCount++; console.log(`Fetching expensive data... (call count: ${this.callCount})`); return `Data fetched at ${new Date().toISOString()}`; } @MemoizeExpiring(3000) // Cache expires after 3 seconds public getExpiringData(param: string): string { console.log(`Fetching expiring data for '${param}'...`); return `Expiring data for ${param} at ${new Date().toISOString()}`; } // Custom hash function for memoizing based on multiple parameters @Memoize((id: number, type: string) => `${id}-${type}`) public getItem(id: number, type: string): string { console.log(`Fetching item ${id} of type ${type}...`); return `Item ${id} (${type}) retrieved at ${new Date().toISOString()}`; } } async function runExample() { const service = new DataService(); console.log("--- Standard Memoize ---"); console.log(service.getExpensiveData()); // Fetches console.log(service.getExpensiveData()); // Returns cached console.log(service.getExpensiveData()); // Returns cached console.log("\n--- Expiring Memoize ---"); console.log(service.getExpiringData("A")); // Fetches console.log(service.getExpiringData("A")); // Returns cached await new Promise(resolve => setTimeout(resolve, 3100)); // Wait for cache to expire console.log(service.getExpiringData("A")); // Fetches again after expiration console.log("\n--- Custom Hash Function Memoize ---"); console.log(service.getItem(1, "book")); // Fetches console.log(service.getItem(1, "book")); // Returns cached console.log(service.getItem(2, "book")); // Different key, fetches console.log(service.getItem(1, "movie")); // Different key, fetches } runExample();
Debug
Known issues
gotchaTypeScript decorators require specific compiler options (`"experimentalDecorators": true` and usually `"emitDecoratorMetadata": true`) in `tsconfig.json` to function correctly.
fix
Ensure `tsconfig.json` includes `"experimentalDecorators": true, "emitDecoratorMetadata": true` under `compilerOptions`.
affects: >=1.0.0
gotchaWhen `@Memoize()` is applied to a method with multiple parameters *without* a custom hash function, it will by default only use the *first* parameter for memoization key generation. Subsequent parameters are ignored for caching purposes, potentially leading to incorrect cached values if the method's result depends on later parameters.
fix
Provide a custom hash function to `@Memoize(hashFunction)` that generates a unique key based on all relevant parameters. For example: `@Memoize((p1, p2) => `${p1}-${p2}`).
affects: >=1.0.0
gotchaThe library does not provide a public API for manual cache invalidation beyond the `MemoizeExpiring` decorator. If you need to clear the cache for a non-expiring memoized method dynamically, you would need to recreate the class instance or implement custom cache invalidation logic.
fix
Consider using `MemoizeExpiring` if you need time-based invalidation, or implement a custom memoization solution or a wrapper around `typescript-memoize` that exposes cache clearing functionality if dynamic invalidation is crucial.
affects: >=1.0.0
Errors
Common errors & fixes
TypeError: Cannot read properties of undefined (reading '__metadata')
TypeScript compiler options for decorators are not correctly configured, often missing `emitDecoratorMetadata`.
fix
Add or ensure `"experimentalDecorators": true` and `"emitDecoratorMetadata": true` in the `compilerOptions` section of your `tsconfig.json`.
TypeError: (0 , typescript_memoize_1.Memoize) is not a function
Attempting to import or use the decorator with CommonJS `require()` syntax or incorrect destructuring in an ES Module context.
fix
Use ES Module import syntax: `import { Memoize } from 'typescript-memoize';`
Upgrade
Version history
1.1.1latest on npm
Audit
Dependencies

No dependency data recorded yet.

Agent activity
17 hits · last 30 days
node
12
OpenAI (training)
2
Resources
typescript-memoize — npm install typescript-memoize · libregistry