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 类型在与映射类型结合使用时变得特别有用,我们稍后会详细了解。

¥keyof types become especially useful when combined with mapped types, which we’ll learn more about later.