Is there a `valueof` similar to `keyof` in TypeScript?
There’s no built-in valueof
keyword in TypeScript similar to keyof
, but you can simulate it by using an indexed access type: T[keyof T]
. Often, people define a helper type alias like:
type ValueOf<T> = T[keyof T];
This yields the union of all property values in T
.
1. Example Usage
type MyObject = { a: string; b: number; }; type Keys = keyof MyObject; // Keys is "a" | "b" type Values = MyObject[keyof MyObject]; // Values is string | number // Or via a helper alias: type ValueOf<T> = T[keyof T]; type MyObjectValues = ValueOf<MyObject>; // string | number
keyof MyObject
→'a' | 'b'
MyObject[keyof MyObject]
→'a'
property type or'b'
property type →string | number
.
2. Working with a Const Object
If you have a literal object with as const
, you can similarly derive all possible values as a type:
const fruits = { apple: "APPLE", banana: "BANANA", cherry: "CHERRY" } as const; type FruitKeys = keyof typeof fruits; // "apple" | "banana" | "cherry" type FruitValues = typeof fruits[keyof typeof fruits]; // "APPLE" | "BANANA" | "CHERRY"
This is the same pattern, just referencing the runtime object fruits
and extracting its type with typeof fruits
.
3. Summary
- There’s no built-in
valueof
keyword, butT[keyof T]
(ortype ValueOf<T> = T[keyof T]
) achieves the same effect, forming a union of all property value types. - This is commonly used to extract possible “value” types from an object or an enum-like structure.
If you’d like to deepen your JavaScript knowledge (and by extension TypeScript), consider the Grokking JavaScript Fundamentals course by DesignGurus.io. It covers key JS concepts such as prototypes, closures, and async patterns—helping you effectively harness advanced TypeScript patterns like these.
CONTRIBUTOR
TechGrind