在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。
答案 0 :(得分:0)
是的,就像这样:
class Animal {
name: string;
type?: any;
}
但我建议使用类似的枚举:
enum AnimalType {Cat, Dog, ...};
class Animal {
name: string;
type?: AnimalType;
}