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
script.ts
interface Person {
name: string;
age: number;
}
// `keyof Person` here creates a union type of "name" and "age", other strings will not be allowed
function printPersonProperty(person: Person, property: keyof Person) {
console.log(`Printing person property ${property}: "${person[property]}"`);
}
let person = {
name: "Max",
age: 27
};
printPersonProperty(person, "name"); // Printing person property name: "Max"
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
script.ts
type StringMap = { [key: string]: unknown };
// `keyof StringMap` resolves to `string` here
function createStringPair(property: keyof StringMap, value: string): StringMap {
return { [property]: value };
}