Keyof Type Operator
Thekeyoftype operator
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 “x” | “y”:
keyof运算符采用对象类型并生成其键的字符串或数字字面量的并集。
type Point = { x: number; y: number };
type P = keyof Point;
type P = keyof Point
Try
If the type has a string or number index signature, keyof will return those types instead:
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
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"].
请注意,在本例中,M 是 string | number-这是因为JavaScript对象键始终强制为字符串,因此obj[0]始终与obj[0]相同
keyof types become especially useful when combined with mapped types, which we’ll learn more about later.
当与映射类型mapped types结合使用时,keyof类型变得特别有用,我们将在后面了解更多。