作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我有一些对象共享很多属性,但有一小部分不同。它们通过 ID 来区分,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 });
}
这似乎是说它不能将所有的枚举值分配给特定的子类型。我不明白为什么这是个问题,因为它与其他类型联合在一起接受所有枚举值。
我做错了什么?
感谢您的帮助。
最佳答案
问题是,当您发送 { id, data }
作为参数时,这会被视为对象字面量类型。
// This function you declared is expecting a SpecificItem type parameter
// and you are sending an object literal type parameter
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;
}
因此,类型不匹配,这就是您收到错误的原因。您需要做的是按照@przemyslaw-pietrzak 的建议发送指定类型的对象,如下所示:
// 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 } as SpecificItem);
}
关于javascript - 枚举联合与枚举不同?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55295632/
我是一名优秀的程序员,十分优秀!