gpt4 book ai didi

javascript - 枚举联合与枚举不同?

转载 作者:行者123 更新时间:2023-11-30 11:06:45 25 4
gpt4 key购买 nike

我有一些对象共享很多属性,但有一小部分不同。它们通过 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 });
}

interactive on the ts site .

这似乎是说它不能将所有的枚举值分配给特定的子类型。我不明白为什么这是个问题,因为它与其他类型联合在一起接受所有枚举值。

我做错了什么?

感谢您的帮助。

最佳答案

问题是,当您发送 { 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com