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 类型在与映射类型结合使用时尤其有用,我们将在后面详细学习映射类型。