Syntax
function get<T, K extends keyof T>(value: T, key: K): T[K] { return value[key]; }Examples
Key Unions with keyof: working example
Run this standalone example after compiling with TypeScript 5.4+ in strict mode, targeting ES2022. Expected result: The program prints 4; uncommenting the missing-key call produces a compile-time error.
function get<T, K extends keyof T>(value: T, key: K): T[K] {
return value[key];
}
const user = { name: "Ada", visits: 3 };
const visits = get(user, "visits");
console.log(visits + 1);
// get(user, "missing"); // Type error: not a key of user.- Expected result: The program prints 4; uncommenting the missing-key call produces a compile-time error.
- K is limited to name or visits for this call.
- T[K] returns number for visits, rather than a broad union of all property types.
Best practices
- Derive key types from the source object instead of maintaining duplicate string unions.
- Validate keys arriving from untyped external data.
Runtime & versions
Compiled to JavaScript. Feature availability depends on the language and runtime version used by your project; consult the official reference below.
TypeScript Handbook