Difference between index signature and Record for empty object?

前端 未结 2 801
别那么骄傲
别那么骄傲 2021-01-02 04:02

I\'m still fairly new to TypeScript and I cannot figure out the difference between between index signatures and record types. Could someone explain the differences and when

2条回答
  •  孤城傲影
    2021-01-02 04:41

    Whether it is a good idea to use Record instead of a plain index signature may be a matter of debate (as David Shereet points out in his answer). Also the fact that you can do a lot more thing with Record then you can with a simple index signature is also something that should be mentioned.

    The main part of this question (in my reading) is whether the two types are the same. They are obviously declared in different ways but are they the same type. While they are obviously compatible (that is you can assign one to the other and vice-versa) the question is are there corner cases where this is not possible.

    While it's hard to find an exhaustive list of what you can do with a type, Matt McCutchen in this answer provides an interesting type that detects weather the readonly modifier is present (something that simple compatibility does not detect the difference between). I would surmise that if Record and an index signature are the considered the same in the way Matt uses them there (as part of the signature of a generic function) they are pretty much the same type declared in a different way:

    type IfEquals =
        (() => T extends X ? 1 : 2) extends
        (() => T extends Y ? 1 : 2) ? "Y" : "N";
    
    let same : IfEquals<{x: string}, {x: string}>= "Y"
    let notsame : IfEquals<{ y: string }, { x: string }>= "N"
    let notsamero: IfEquals<{ readonly x: string }, { x: string }> = "N"
    let samerecord: IfEquals<{ [x: string]:string }, Record> = "Y"
    

    As we can see in the last example the type of samerecord is Y meaning that the compiler treated the two types as being the same thing. Thus I would surmise { [x: string]:string } and Record are exactly the same thing.

提交回复
热议问题