Flash cards
Review the key moves
1/4
Core idea
What is the main idea behind TypeScript Keyof?
Lesson checks
Practice each idea before moving on
Short Mimo-style checks built from this lesson's code, terms, and sequence.
1Quick choice
Which statement best captures the main point of this lesson?
2Fill blank
Complete the missing token from the example code.
___ Person {3Order
Put the learning moves in the order that makes the concept easiest to apply.
keyof is a keyword in TypeScript which is used to extract the key type from an object type.
keyof with index signatures
keyof with explicit keys
keyof is a keyword in TypeScript which is used to extract the key type from an object type.
keyof with explicit keys
When used on an object type with explicit keys, keyof creates a union type with those keys.
Example
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 can also be used with index signatures to extract the index type.
Example
type StringMap = { [key: string]: unknown };
// `keyof StringMap` resolves to `string` here function createStringPair(property: keyof StringMap, value: string): StringMap {
return { [property]: value };
}