Skip to content

Keyof

keyof gets you a union of an object’s keys. Handy when you need to reference property names in a type-safe way.

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 also works with index signatures to get the index type.

type StringMap = { [key: string]: unknown };
// Here, `keyof StringMap` resolves to a `string`
function createStringPair(property: keyof StringMap, value: string): StringMap {
  return { [property]: value };
}