[英]Why does `keyof any` have type of `string | number | symbol` in typescript?
The type Record
in typescript is defined as: 打字稿中的
Record
类型定义为:
type Record<K extends keyof any, T> = {
[P in K]: T;
}
I don't understand why keyof any
is used here. 我不明白为什么在这里使用了
keyof any
。
After checking I found that the type of keyof any
is string | number | symbol
检查后,我发现
keyof any
的键类型是string | number | symbol
string | number | symbol
string | number | symbol
. string | number | symbol
。 Why is that? 这是为什么?
keyof any
represents the type of any value that can be used as an index to an object. keyof any
表示可以用作对象索引的任何值的类型。 Currently you can use string
or number
or symbol
to index into an object. 当前,您可以使用
string
, number
或symbol
来索引到对象中。
let a: any;
a['a'] //ok
a[0] // ok
a[Symbol()] //ok
a[{}] // error
In the Record
type, this K extends keyof any
is used to constrain K
to something that is a valid key for an object. 在“
Record
类型中,此K extends keyof any
的键用于将K
约束为某个对象的有效键。 So K
could be 'prop'
or '1'
or string
but not {a : string}
: 因此
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
The constraint is there, since whatever type is passed in K
will become the keys of the resulting type, and thus K
must be something that is a valid key for an object. 约束在那里,因为在
K
传递的任何类型都将成为结果类型的键,因此K
必须是对对象有效的键。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.