Why does `keyof any` have type of `string | number | symbol` in typescript?

后端 未结 1 708
花落未央
花落未央 2021-02-19 22:00

The type Record in typescript is defined as:

type Record = {
    [P in K]: T;
}         


        
1条回答
  •  予麋鹿
    予麋鹿 (楼主)
    2021-02-19 22:33

    keyof any represents the type of any value that can be used as an index to an object. Currently you can use string or number or symbol to index into an object.

    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. So K could be 'prop' or '1' or string but not {a : string}:

    type t0 = Record<1, string> // { 1: string }
    type t1 = Record<"prop", string> // { prop: string }
    type t3 = Record // { [name: string]: string }
    type t4 = Record // { [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.

    0 讨论(0)
提交回复
热议问题