Keyof Type Operator

The keyof type operator

The keyof operator takes an object type and produces a string or numeric literal union of its keys. The following type P is the same type as type P = "x" | "y":

Try this code ↗

type Point = { x: number; y: number };
typeP = keyofPoint;

type P = keyof Point

If the type has a string or number index signature, keyof will return those types instead:

Try this code ↗

type Arrayish = { [n: number]: unknown };
typeA = keyofArrayish;

type A = number

typeMapish = { [k: string]: boolean };
typeM = keyofMapish;

type M = string | number

Note that in this example, M is string | number — this is because JavaScript object keys are always coerced to a string, so obj[0] is always the same as obj["0"].

keyof types become especially useful when combined with mapped types, which we’ll learn more about later.

Last updated on