keyof 类型运算符

keyof 类型运算符

🌐 The keyof type operator

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

🌐 The keyof operator takes an object type and produces a string or numeric literal union of its keys. The following type P is the same type as type P = "x" | "y":

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

如果该类型有 stringnumber 索引签名,keyof 将返回这些类型:

🌐 If the type has a string or number index signature, keyof will return those types instead:

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"] 相同。

🌐 Note that in this example, M is string | number — this is because JavaScript object keys are always coerced to a string, so obj[0] is always the same as obj["0"].

keyof 类型在与映射类型结合使用时尤其有用,我们将在后面详细学习映射类型。