2016-03-09 155 views
0

在TypeScript中,类型声明可以允许动态对象属性?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

是的,是这样的:

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

但我会建议使用一个枚举类型这样的:

enum AnimalType {Cat, Dog, ...}; 

class Animal { 
    name: string; 
    type?: AnimalType; 
} 
+0

什么'colour'例如?我希望允许额外的属性而不必将它们添加到类型中。 – user3233089

+0

这应该不会有任何错误:请参阅http://www.typescriptlang.org/Playground#src=class%20Animal%20%7B%0A%20%20%20%20name%3A%20string%3B%0A %7D%0A%0Alet%20动物%20%3D%20%3动物%3E%7B%20名称%3A%20%22Kitty%22%2C%20型%3A%20%22%22%20%7D%3B –

+0

It确实。 http://www.typescriptlang.org/Playground#src=class%20Animal%20%7B%0A%20%20%20%20name%3A%20string%3B%0A%7D%0A%0Alet%20animal%20% 3D%20%3CAnimal%3E%7B%20name%3A%20%22Kitty%22%2C%20type%3A%20%22cat%22%20%7D%3B%0A%0Aanimal.type%20%3D%20123% 3B – user3233089