TypeMap Keyed Heterogeneous Stores
Wrap Map with a TypeMap parameter so each key keeps its own value type — plain Map<K, V> forces one V across every key.
Code
// Map can only give one value type V, so wrap it with a TypeMap parameter
type FieldTypes = {
name: string;
retries: number;
tags: string[];
};
class TypedStore<M extends Record<keyof M, unknown>> {
#data = new Map<keyof M, unknown>();
set<K extends keyof M>(key: K, value: M[K]): this {
this.#data.set(key, value);
return this;
}
get<K extends keyof M>(key: K): M[K] | undefined {
return this.#data.get(key) as M[K] | undefined;
}
}
const store = new TypedStore<FieldTypes>();
store.set('name', 'primary').set('retries', 3).set('tags', ['edge']);
// Each get call is typed by its own key, not by one shared V
const name: string | undefined = store.get('name');
const retries: number | undefined = store.get('retries');
const tags: string[] | undefined = store.get('tags');
console.log(name, retries, tags);Output
Captured from a sandboxed run of this snippet in the build pipeline.
primary 3 [ 'edge' ]How it works
Everything happens inside the class TypedStore.
The file’s state is a handful of top-level bindings: store.
Caveats
- Dependency-free by construction — no registry, no lockfile entry.
Key statements
set<K extends keyof M>(key: K, value: M[K]): this {
this.#data.set(key, value);
return this;
}
get<K extends keyof M>(key: K): M[K] | undefined {
return this.#data.get(key) as M[K] | undefined;
}
Interactive Tools for This Topic
FAQ
- Are there dependencies to manage?
- No. There are no dependencies to declare or install. Its state lives in module-level bindings: `store`.
Report a problem with this exampleOpens a pre-filled issue on GitHub.