【发布时间】:2020-10-03 19:35:54
【问题描述】:
我想使用 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 }
};
【问题讨论】:
标签: typescript object types enums