【问题标题】:"Consider using a mapped object type instead." - what's a mapped object type and how do I use it here?“考虑改用映射对象类型。” - 什么是映射对象类型,我如何在这里使用它?
【发布时间】:2018-08-02 17:43:35
【问题描述】:
interface Foo { 
    [foo: "hello" | "world"]: string;
}

我收到类似的错误消息

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

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

【问题讨论】:

    标签: typescript


    【解决方案1】:

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

    例如,这个:

    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

    【讨论】:

    • 是否有这样的版本,其中类型只能具有一个名称必须为 hello 或 world 的属性?
    • 我想指出不同之处。为了创建一个映射类型,我们将 ":" 替换为 " 中的 "。并变成[foo in "hello" | "world"]
    • 请注意答案将interface 更改为type - 这是我的解决方案。
    • @ironchicken,是的,你只需要在关闭]后添加?,更多细节在这里:stackoverflow.com/a/52700831/449553
    • @ironchiken 你可以做type Foo = { hello: string; world?: never; } | { world: string; hello?: never }。您还可以扩展它以接受通用联合/值以使其可重用:type Foo = OnlyOneProperty<"hello" | "world", string>。用法见playground。
    【解决方案2】:

    这是无效的:

        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 = {};
        }
    

    【讨论】:

    • 您能否更深入地了解您的答案?试图在没有解释的情况下理解答案可能会导致误解。
    • 我能够通过在“DirectiveType”末尾使用“as string”从联合类型推断映射对象的键
    • 这是更好的答案,因为它保留了指定密钥类型的能力,并且有多个接口使用该类型作为密钥。接受的答案范围更有限,对我的需求几乎没有用。
    猜你喜欢
    • 2017-04-01
    • 1970-01-01
    • 2019-01-22
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-04-04
    • 2021-12-11
    • 2011-01-12
    相关资源
    最近更新 更多