简体   繁体   English

为什么`keyof any`具有`string |类型? 编号 打字稿中的符号`?

[英]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. 当前,您可以使用stringnumbersymbol来索引到对象中。

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.

相关问题 TypesScript:为什么 keyof {} 没有类型? - TypesScript: Why does keyof {} have the type never? Typescript - 索引表达式参数必须是&#39;string&#39;,&#39;number&#39;,&#39;symbol&#39;或&#39;any&#39;类型 - Typescript - An index expression argument must be of type 'string', 'number', 'symbol' or 'any' TypeScript - 计算属性名称的类型必须为“字符串”、“数字”、“符号”或“任意” - TypeScript - A computed property name must be of type 'string', 'number', 'symbol', or 'any' 打字稿错误:计算的属性名称必须是“字符串”、“数字”、“符号”或“任何”类型 - Typescript error: A computed property name must be of type 'string', 'number', 'symbol', or 'any' 在打字稿中指定 keyof 类型 - specify keyof type in typescript 为什么 typescript 没有“功能”类型? - Why typescript does not have “function” type? 为什么打字稿接受数字值作为类型? - Why does typescript accept a number value as a type? 为什么 Typescript 允许将“任何”对象类型分配给类对象? - Why does Typescript allow to assign an “any” object type to class object? 为什么要声明类型 <any> 解决未知方法错误? (打字稿) - Why Does Declaring Type <any> Resolve Error with Unknown Method? (Typescript) TypeScript数组类型转换与keyof like方法 - TypeScript array type transform with keyof like method
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM