我想使用TypeScript类型强类型festivals
对象。每个属性始终为IFestival
类型。我不想像以前那样定义IFestivals
,因为还有大约20多个属性。有没有办法告诉TypeScript与对象关联的每个属性都属于同一类型?有点像您可以type IFestivals = Array<IFestival>
,但IFestivals = Object<IFestival>
可以做什么?
以下代码:
interface IFestival {
name: string;
festival?: boolean;
favourite?: boolean;
}
// I do not want to define it this way as there are 25+ attributes like this in reality...
interface IFestivals extends Object {
BESTIVAL: IFestival;
GLASTONBURY: IFestival;
LOVEBOX: IFestival;
MIGHTY_HOOPLA: IFestival;
PARKLIFE: IFestival;
}
const festivals: IFestivals = {
BESTIVAL: { name: "Bestival", festival: true },
GLASTONBURY: { name: "Glastonbury", festival: true, favourite: true },
LOVEBOX: { name: "Lovebox", festival: true },
MIGHTY_HOOPLA: { name: "Mighty Hoopla", festival: true },
PARKLIFE: { name: "Parklife", festival: true }
};
答案 0 :(得分:0)
除非您要使用不控制属性名称的indexed type(或Map<string,IFestival>
)(您只能按string | number
或{{1}进行索引},而不是枚举或类似名称):
number
...那么您将要编写某事 25次。真的没什么大不了的。
您最好的选择是做自己做的事情,尽管没有隐式的type IFestivals = {[name: string]: IFestival};
:
extends Object
但是,如果您需要拥有这25个属性,并且在一个接口中具有一种类型,而在另一个接口中具有另一种类型,则可以使用泛型:
interface IFestivals {
BESTIVAL: IFestival;
GLASTONBURY: IFestival;
LOVEBOX: IFestival;
MIGHTY_HOOPLA: IFestival;
PARKLIFE: IFestival;
// ...
}
但是,没有理由为单个界面执行该操作。