Difference between index signature and Record for empty object?

前端 未结 2 799
别那么骄傲
别那么骄傲 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:49

    The definition for Record is:

    /**
     * Construct a type with a set of properties K of type T
     */
    type Record = {
        [P in K]: T;
    };
    

    When creating a type like type MyType = Record;, inlining Record leads to the following type:

    type MyType = {
        [P in string]: string;
    };
    

    This is saying to create an object type with string property names within the set string. Since string is unbounded there's unlimited possibilities of strings (unlike a union of string literal types like "prop1" | "prop2")... so it's describing an object that can have any number of properties with any name, with the only restriction being that the properties must have a type of string.

    So yes, from a type checking perspective it's basically equivalent to the example with the index signature without a mapped type ({ [index: string]: string; }.

    Use a plain index signature

    Using Record in this fashion is a little strange though and many people might not understand what's going on. A more common way to express intent when there can be any number of properties, is to not use a mapped type:

    type ObjectWithStringProperties = {
        [index: string]: string;
    };
    

    This has the added benefit of helping explain what the key is supposed to be. For example:

    type PersonsByName = {
        [name: string]: Person;
    };
    const collection: PersonsByName = {};
    

    Note that in this way the types are different because a developer using an object with this type will have this extra described key name information to look at in their editor.

    Using Record

    Note that Record is usually used like the following:

    type ThreeStringProps = Record<"prop1" | "prop2" | "prop3", string>;
    // goes to...
    type ThreeStringProps = { [P in "prop1" | "prop2" | "prop3"]: string; };
    // goes to...
    type ThreeStringProps = {
        prop1: string;
        prop2: string;
        prop3: string;
    };
    

提交回复
热议问题