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.

TypescriptData Fetching

Code

typescriptsnippet
31 lines
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;
  }
}

What to watch for

  • No external packages — everything relies on the language’s built-in APIs.
  • The guard !entry short-circuits bad input before any real work happens.

Using it

TypedCache is the public entry point; everything else in the file exists to support it.

The crux of the implementation is this line:

this.store.set(key, { value, expiresAt: Date.now() + this.ttlMs });

One more line that carries real weight:

private store = new Map<K, { value: V; expiresAt: number }>();

And the line that closes the loop:

private onEvict?: (key: K, value: V) => void,

Interactive Tools for This Topic

FAQ

Does this require external packages?
No. It relies only on built-in language and platform APIs, so you can paste it into a project without installing anything.