keyof 类型运算符
¥The keyof type operator
keyof 运算符采用对象类型并生成其键的字符串或数字字面联合。以下类型 P 与 type 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":
tsTrytypePoint = {x : number;y : number };typeP = keyofPoint ;
如果该类型具有 string 或 number 索引签名,则 keyof 将返回这些类型:
¥If the type has a string or number index signature, keyof will return those types instead:
tsTrytypeArrayish = { [n : number]: unknown };typeA = keyofArrayish ;typeMapish = { [k : string]: boolean };typeM = keyofMapish ;
请注意,在这个例子中,M 是 string | 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.