The keyof
type operator
The keyof
operator takes an object type and produces a string or numeric literal union of its keys:
Try
typePoint = {x : number;y : number };type// ^ = type P = keyof PointP = keyofPoint ;
If the type has a string
or number
index signature, keyof
will return those types instead:
typeArrayish = { [n : number]: unknown };type// ^ = type A = numberA = keyofArrayish ;Try
typeMapish = { [k : string]: boolean };type// ^ = type M = string | numberM = keyofMapish ;
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.