【问题标题】:TypeScript dynamic object propertiesTypeScript 动态对象属性
【发布时间】:2016-03-09 10:09:54
【问题描述】:

在 TypeScript 中,类型声明可以允许动态对象属性吗?

class Animal {
    name: string;
    [everything else]: any;
}

let animal = <Animal>{ name: "Kitty", type: "cat" };

animal.name; // Would be treated as string

animal.type; // Would allow compilation and be treated as any

我希望动态允许这些额外的属性,而不必将它们添加到类型声明中。使用 TypeScript 1.8.2。

【问题讨论】:

    标签: typescript typescript1.8


    【解决方案1】:

    是的,像这样:

    class Animal {
        name: string;
        type?: any;
    }
    

    但我建议对这样的类型使用 Enum:

    enum AnimalType {Cat, Dog, ...};
    
    class Animal {
        name: string;
        type?: AnimalType;
    }
    

    【讨论】:

    猜你喜欢
    • 2018-07-06
    • 2020-10-07
    • 2018-08-13
    • 2021-02-27
    • 2019-08-23
    • 2017-09-06
    • 1970-01-01
    相关资源
    最近更新 更多