TypeScript keyof


keyof是 TypeScript 中的一个关键字,用于从对象类型中提取键类型。


keyof使用显式键

当用于具有显式键的对象类型时,keyof使用这些键创建联合类型。

示例

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带索引签名

keyof还可以与索引签名一起使用来提取索引类型。

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