【发布时间】:2019-03-22 08:31:35
【问题描述】:
我有一些对象共享很多属性,但有一小部分是不同的。它们的区别在于它们的 ID,它是枚举中的一个值。我想将它们键入为相同泛型的子类型,以便利用类型保护来了解哪些属性是可访问的。
例子:
enum ItemIDs {
ITEM_TYPE_1,
ITEM_TYPE_2
}
// Generic item with shared properties
interface GenericItem<ID, Data> {
id: ID
data: Data
}
// Specific items where the 'data' property can be different shapes
type SpecificItemOne = GenericItem<ItemIDs.ITEM_TYPE_1, { content: string }>
type SpecificItemTwo = GenericItem<ItemIDs.ITEM_TYPE_2, { amount: number }>
// Specific item is a union of all specific items
type SpecificItem = SpecificItemOne | SpecificItemTwo;
// Take item and test that typescript can work out what properties are available
// It works!
const testTypeGuard = (item: SpecificItem) => {
if (item.id === ItemIDs.ITEM_TYPE_1) {
item.data.content = ''
} else if (item.id === ItemIDs.ITEM_TYPE_2) {
item.data.amount = 0;
}
return item;
}
// Try to create item where ID can be any from ID enum
const breakTypeGuard = (id: ItemIDs, data: any) => {
// Type 'ItemIDs' is not assignable to type 'ItemIDs.ITEM_TYPE_2'.
// WHY
testTypeGuard({ id, data });
}
似乎是说它不能将所有枚举值分配给特定的子类型。我不明白为什么这是一个问题,因为它与其他类型联合在一起确实接受所有枚举值。
我做错了什么?
感谢您的帮助。
【问题讨论】:
标签: javascript typescript enums