Generic Cache With Eviction Hook
Build a key-value cache that is generic over value type and fires an eviction callback, so callers get typed reads and can clean up resources.
Code
export class TypedCache<K, V> {
private store = new Map<K, { value: V; expiresAt: number }>();
constructor(
private ttlMs: number,
private onEvict?: (key: K, value: V) => void,
) {}
get(key: K): V | undefined {
const entry = this.store.get(key);
if (!entry) return undefined;
if (entry.expiresAt <= Date.now()) {
this.store.delete(key);
this.onEvict?.(key, entry.value);
return undefined;
}
return entry.value;
}
set(key: K, value: V): void {
if (this.store.has(key)) {
const previous = this.store.get(key)!;
this.onEvict?.(key, previous.value);
}
this.store.set(key, { value, expiresAt: Date.now() + this.ttlMs });
}
size(): number {
return this.store.size;
}
}Report a problem with this exampleOpens a pre-filled issue on GitHub.