TypeScript Dictionary Factory Function with Type Hints
The article introduces a TypeScript dictionary factory that, using generics and `as const` assertions, converts a single source definition into multiple strongly‑typed representations (KV, VK, list, maps), eliminating duplication and keeping business dictionaries synchronized while providing full IntelliSense, albeit with some TypeScript‑only limitations.
In business development, defining enumeration values often leads to multiple associated dictionaries (e.g., mapping types to names, icons, or list items). Maintaining separate dictionaries causes duplication, inconsistency, and maintenance overhead when types change.
The article proposes a dictionary factory function that transforms a single source definition into various formats: key‑value (KV), value‑key (VK), list, map‑by‑key, and map‑by‑value.
Initially, a JavaScript implementation accepts an array of objects describing each dictionary item and returns an object containing the different representations.
To add type safety, the factory is rewritten in TypeScript using generics. The base interface IBaseDef defines the required key and value properties, while additional fields (name, icon, etc.) are allowed.
The return type is built with several type‑level helper functions: ToProperty generates prefixed keys, MergeIntersection intersects multiple object types, ToSingleKeyValue converts a single tuple to a key‑value type, and ToKeyValue recursively processes a tuple list into a combined key‑value type.
The factory function is constrained to accept readonly arrays and requires the caller to use as const assertions so that literal values are preserved for type inference.
Example usage shows defining a music type dictionary and obtaining strongly typed constants such as MUSIC_TYPE_KV, MUSIC_TYPE_LIST, etc., with full IntelliSense support.
The article also discusses limitations: the factory works only in TypeScript projects, relies on as const, cannot retain JSDoc comments in the generated types, and does not export type definitions alongside the values, requiring separate type exports.
Despite these drawbacks, the dictionary factory provides a clean, reusable way to keep business dictionaries synchronized and type‑safe.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
