Codectionary / Developer documentation / TypeScript

Key Unions with keyof

keyof derives a union of property keys from an object type. Combined with a constrained type parameter, it prevents callers from requesting nonexistent properties while preserving the return type for the selected key. It operates during type checking and emits no runtime validation.

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.
  1. Expected result: The program prints 4; uncommenting the missing-key call produces a compile-time error.
  2. K is limited to name or visits for this call.
  3. 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

Specifications & further reading