TypeScript Keyof Operator
TypeScript Keyof Operator
The TypeScript keyof operator is used to extract the key type from an object type.
Keyof with explicit keys
When used on an object type with explicit keys, the keyof
operator 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"
Try it Yourself »
Keyof with index signatures
The keyof operator 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 };
}
Try it Yourself »