代码之家  ›  专栏  ›  技术社区  ›  Daniel Rosenwasser

“考虑使用映射对象类型。”什么是映射对象类型?我在这里如何使用它?

  •  14
  • Daniel Rosenwasser  · 技术社区  · 8 年前
    interface Foo { 
        [foo: "hello" | "world"]: string;
    }
    

    我收到一条错误信息,比如

    An index signature parameter type cannot be a union type. Consider using a mapped object type instead.
    

    什么是映射对象类型,如何使用它?

    1 回复  |  直到 8 年前
        1
  •  139
  •   Daniel Rosenwasser    5 年前

    映射对象类型对一组单例类型进行操作,并生成一个新的对象类型,其中每个单例都转换为属性名称。

    例如:

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

    相当于

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

    请记住,映射的对象类型是一个独特的类型运算符——大括号中的语法不能用于接口,也不能用于其他成员的对象类型。例如

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

    产生以下错误:

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

    映射对象类型对于许多不同的事情都很有用。请在此处阅读更多内容: http://www.typescriptlang.org/docs/handbook/advanced-types.html#mapped-types

        2
  •  1
  •   ChrisKader    4 年前

    这是无效的:

        type DirectiveType = 'package-as' | 'externals' | 'move-folders' | 'ignore';
        type Directives = { [key:DirectiveType]?: RootDirectives };
        
        export class PkgmetaFile {
            private _directives: Directives = {};
        }
    

    但这是正确的:

        type DirectiveType = 'package-as' | 'externals' | 'move-folders' | 'ignore';
        type Directives = { [Key in DirectiveType as string]?: RootDirectives };
        
        export class PkgmetaFile {
            private _directives: Directives = {};
        }
    
    推荐文章