TypeScript Snippet

ValueOf Utility Type

Difficulty: Easy

`keyof` gives you the union of property names; `ValueOf<T>` gives you the union of property values. Combined with `as const` it derives a string-literal union from a single source-of-truth object, so the runtime constant and the static type can never drift. This snippet covers the one-line definition, an enum-replacement pattern, and a discriminator helper that drives type-safe `switch` blocks.

Code Snippets
/

ValueOf Utility Type

ValueOf Utility Type

`keyof` gives you the union of property names; `ValueOf<T>` gives you the union of property values. Combined with `as const` it derives a string-literal union from a single source-of-truth object, so the runtime constant and the static type can never drift. This snippet covers the one-line definition, an enum-replacement pattern, and a discriminator helper that drives type-safe `switch` blocks.

TypeScript
Easy
3 snippets
ts-utility-types
ts-mapped-types
ts-generics
code-template

1,173 views

25

T[keyof T] indexes a type by all of its keys at once, which TypeScript expands into the union of all property value types. With as const, the literal types stay narrow (1 | 2 | 3 instead of number), so SeverityValue becomes a precise sentinel-set the compiler can exhaustively check. The pattern fits anywhere you would have reached for a numeric or string enum but want a plain object that survives JSON.stringify and tree-shakes cleanly. The runtime behavior is just an object lookup, no extra emit cost.