Skip to main content

TypeScript Keyof

keyof is a TypeScript keyword. It takes an object type and gives you the type of its keys.


keyof with explicit keys

When you use keyof on an object type that lists its properties by name, the result is a union type made of those property names.

Example

keyof Person becomes the union "name" | "age". Passing any other string to the function is an error.

Prompt
Show how keyof on an interface with named properties produces a union of those property names. Declare a Person interface with name: string and age: number, write a function that takes a Person and a keyof Person property name and logs that property's value, then call it with a person named Max, age 27, and the property "name".
Output: TypeScript file and captured output

keyof with index signatures

keyof also works on types with an index signature. In that case it gives you the index type.

Example

Because StringMap accepts any string key, keyof StringMap is simply string.

Prompt
Show that keyof applied to a type with a string index signature resolves to string. Define a StringMap type with a [key: string]: unknown index signature and a function that takes a keyof StringMap key plus a string value and returns a new StringMap holding that pair; the example only declares, it prints nothing.
Output: TypeScript file and captured output