TypeScript Reference ยท Generics
Generic constraints with keyof
Reference for the TypeScript K extends keyof T pattern: write type-safe property getters, setters, pluck and pick functions with indexed access types.
The pattern K extends keyof T constrains one type parameter to be a valid key of another. Combined with the indexed access type T[K], it lets a function accept an object and a property name and return exactly the type of that property. The compiler rejects names that do not exist.
It is the foundation of typed get, set, pluck, groupBy and sortBy helpers, and of many built-in utility types.
function getProp<T, K extends keyof T>(obj: T, key: K): T[K] { return obj[key]; }
Try it
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Press Run (or Ctrl + Enter) to see the result here.
Program input ยท what you'd type while the program runs
Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.
Syntax
function f<T, K extends keyof T>(obj: T, key: K): T[K]; function g<T extends object, K extends keyof T = keyof T>(obj: T): T[K][]; type Getter<T, K extends keyof T> = (obj: T) => T[K];
| Part | Description |
|---|---|
keyof T |
The union of all known public property names of T as literal types (string, number or symbol). |
K extends keyof T |
K is one (or a union) of those keys; the literal type is kept, so T[K] is precise. |
T[K] |
Indexed access type: the type of property K of T. With a union K, the result is a union of those property types. |
Edge cases: keyof of a type with an index signature includes string | number (or number). keyof any is string | number | symbol. For an array type, keyof includes number and method names.
Usage notes
- Why two parameters. Typing the key as plain
stringwould allow any name andT[string]would not compile.K extends keyof Tkeeps the literal name so the compiler can look the property type up. - Unions of keys work.
getProp(user, k)withk: "name" | "age"returnsstring | number. - Writing is stricter. For
setPropwith a union key,T[K]becomes an intersection on the write side, which is why safe setters usually take a single key. - Only known keys.
keyofdoes not see properties added at runtime. For free-form maps use an index signature orRecord<string, V>. string & keyof Tnarrows to string keys when you needCapitalize<K>or template literals, becausekeyofmay include numbers and symbols.- Need the key from a value? Use
Object.keys(obj) as (keyof T)[]with care: objects can hold extra properties at runtime. - Alternatives. Mapped types can express the same lookups across all keys at once (
{ [K in keyof T]: ... }).