keyof 类型运算符

keyof 类型运算符

keyof 运算符接受对象类型,并生成其键的字符串或数字字面量联合类型。下面的类型 Ptype P = "x" | "y" 相同:

ts
type Point = { x: number; y: number };
type P = keyof Point;
type P = keyof Point
Try

如果类型具有 stringnumber 索引签名,keyof 将返回相应的类型:

ts
type Arrayish = { [n: number]: unknown };
type A = keyof Arrayish;
type A = number
 
type Mapish = { [k: string]: boolean };
type M = keyof Mapish;
type M = string | number
Try

请注意,在此示例中,Mstring | number——这是因为 JavaScript 对象的键总是被强制转换为字符串,所以 obj[0] 总是等同于 obj["0"]

当与映射类型结合使用时,keyof 类型变得非常有用,我们稍后将详细了解。

The TypeScript docs are an open source project. Help us improve these pages by sending a Pull Request

Contributors to this page:
  (6)

Last updated: 2024年10月10日