Skip to content
Tutorials Center
My learning

Topics

TypeScript Reference ยท Type Operators

The TypeScript keyof operator

Reference for the TypeScript keyof type operator: the union of an object type's keys, keyof with index signatures, arrays and generics, and typed property access.

keyof T produces a union of the known property names of the type T, as string, number or symbol literal types. For { id: number; name: string } it is "id" | "name". It is a type-level operator: it exists only for the compiler and emits nothing.

Its main job is to type code that accesses properties by name: function get<T, K extends keyof T>(obj: T, key: K): T[K] guarantees that the key exists and that the result has the right type. It is also the foundation of mapped types such as Partial, Pick and Record.

TypeScript
type User = { id: number; name: string };
type UserKey = keyof User; // "id" | "name"

Try it

TypeScript Typed property access

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.

TypeScript Index signatures, arrays and typeof

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

TypeScript
type Keys = keyof T;
function f<K extends keyof T>(key: K): T[K];
type Names = keyof typeof someValue;
Input type T Result of keyof T
Object with properties Union of literal property names (string, number and unique symbol literals).
{ [k: string]: V } string | number (numeric keys are valid string keys).
{ [k: number]: V } number.
A | B Keys present in both.
A & B Keys of either.
any string | number | symbol.
unknown, never never for unknown; string | number | symbol for never.

Edge cases: keyof returns only public members of a class type; private and #private names are excluded. Optional properties are included. With the older keyofStringsOnly option (deprecated and removed in recent TypeScript versions), keyof returned only strings.

Usage notes

  • Strings only: wrap with Extract<keyof T, string> or string & keyof T when you need names for template literal types.
  • Not a runtime list: to get keys at runtime use Object.keys, which returns string[]; cast carefully because objects can hold extra properties.
  • Lookup types: T[keyof T] is the union of all value types of T.
  • Readonly and optional modifiers do not change keyof.
  • Mapped type remapping: as clauses in mapped types can filter or rename the keys produced by keyof.
  • Sibling operator: typeof takes a value to its type, so keyof typeof obj gets keys of a value.