Keyof
the keyof
keyword is utilized to extract the type of keys from an object type. When applied to an object type that has explicit keys, keyof
generates a union type encompassing those keys.
interface Employee {
name: string;
age: number;
}
function printEmployeeProperty(employee: Employee, property: keyof Employee) {
console.log(
`Printing employee property ${property}: "${employee[property]}"`
);
}
// `keyof Employee` here creates a union type of "name" and "age",
// other strings will not be allowed
let employee = {
name: 'Matt',
age: 30,
};
printEmployeeProperty(employee, 'name'); // Printing employee
// property name: "Matt"
keyof
using index signatures
the keyof
keyword can also be employed with index signatures to extract the type of indexes.
type StringMap = { [key: string]: unknown };
// Here, `keyof StringMap` resolves to a `string`
function createStringPair(property: keyof StringMap, value: string): StringMap {
return { [property]: value };
}