“Consider using a mapped object type instead.” - what's a mapped object type and how do I use it here?

前端 未结 1 1088
说谎
说谎 2021-02-03 16:50
interface Foo { 
    [foo: \"hello\" | \"world\"]: string;
}

I get an error message like

An index signature parameter type cannot be a          


        
相关标签:
1条回答
  • 2021-02-03 17:24

    A mapped object type operates on a set of singleton types and produces a new object type where each of those singletons is turned into a property name.

    For example, this:

    type Foo = {
        [K in "hello" | "world"]: string
    };
    

    would be equivalent to

    type Foo = {
        "hello": string;
        "world": string;
    };
    

    Keep in mind that a mapped object type is a distinct type operator - that syntax in the braces can't be used in interfaces, or object types with other members. For example

    interface Foo {
        [K in "hello" | "world"]: string
    }
    

    produces the following error:

    A computed property name in an interface must refer to an expression whose type is a literal type or a 'unique symbol' type.
    

    Mapped object types are useful for a lot of different things. Read more here: http://www.typescriptlang.org/docs/handbook/advanced-types.html#mapped-types

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