类型Record
在typescript中定义为:
type Record<K extends keyof any, T> = {
[P in K]: T;
}
我不明白这里为什么要用keyof any
。
检查后发现keyof any
的类型是string |编号 |符号
。这是为什么?
最佳答案
keyof any
表示可用作对象索引的任何值的类型。目前,您可以使用 string
或 number
或 symbol
对对象进行索引。
let a: any;
a['a'] //ok
a[0] // ok
a[Symbol()] //ok
a[{}] // error
在Record
类型中,此K extends keyof any
用于将K
限制为对象的有效键。所以 K
可以是 'prop'
或 '1'
或 string
但不是 {a : string
:
type t0 = Record<1, string> // { 1: string }
type t1 = Record<"prop", string> // { prop: string }
type t3 = Record<string, string> // { [name: string]: string }
type t4 = Record<number, string> // { [name: number]: string }
type t5 = Record<{a : string}, string> // error
约束就在那里,因为在 K
中传递的任何类型都将成为结果类型的键,因此 K
必须是对于一个对象。
关于javascript - 为什么 `keyof any` 在 typescript 中的类型为 `string | number | symbol`?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55535598/