keyof (TypeScript)

The `keyof` operator produces a union of the property names (keys) of a type. For an object type, `keyof T` is a literal union of all its key strings.

TypeScript

`keyof` is a type-level operator, used in type annotations rather than in runtime code. It is often paired with generics to write functions that safely access a property by name.

A classic example is a typed `get` helper: by constraining a key parameter to `keyof T`, the compiler rejects any key that doesn't exist on the object.

Syntax

keyof T

Examples

TypeScript

interface User {
  name: string;
  age: number;
}

type UserKey = keyof User; // "name" | "age"

function get(u: User, key: keyof User) {
  return u[key];
}

console.log(get({ name: "Ana", age: 30 }, "name"));

Output:

Ana

Learn it in a lesson

See also

Back to the Dictionary