【发布时间】:2019-12-13 06:05:26
【问题描述】:
我正在定义一个接口,其中一种属性类型取决于绑定到枚举的通用参数 P。我正在使用以下方法:
export enum Scopes {
Fruit = 'fruit',
Vegetables = 'vegetables',
}
export enum FruitItemTypes {
Strawberry = 'strawberry',
Rasberry = 'rasberry'
}
export enum VegetableItemTypes {
Potatoes = 'potatoes',
Carrots = 'currency',
}
export type ItemTypes = FruitItemTypes | VegetableItemTypes
interface ItemTypeForScope {
[Scopes.Fruit]: FruitItemTypes;
[Scopes.Vegetables]: VegetableItemTypes;
}
export interface Item {
id: string;
type: ItemTypes;
}
export interface ScopedItem<T extends Scopes> extends Item {
type: ItemTypeForScope[T];
}
export interface ScopedData<T extends Scopes> {
items: ScopedItem<T>[];
}
export type Data = { [scope in Scopes]: ScopedData<scope> };
我也想用ScopedItem<T>作为下面函数的返回类型:
const getItemType = <T extends Scopes>(data: Data, scope: T): ScopedItem<T>[] => {
return data[scope].items
}
但是我收到以下错误,但根据我的说法,通用参数 T 最终将成为枚举案例之一。
Type 'ScopedItem<Scopes.Fruit>[] | ScopedItem<Scopes.Vegetables>[]' is not assignable to type 'ScopedItem<T>[]'.
Type 'ScopedItem<Scopes.Fruit>[]' is not assignable to type 'ScopedItem<T>[]'.
Type 'ScopedItem<Scopes.Fruit>' is not assignable to type 'ScopedItem<T>'.
Type 'Scopes.Fruit' is not assignable to type 'T'.
'Scopes.Fruit' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint 'Scopes'.
【问题讨论】:
-
关于你的游乐场链接......那些不是联合和交叉点。您使用的 logical operators 非常不同。
x || y和x && y将始终评估为x或y之一,具体取决于x的真实性/虚假性。 -
感谢详细解答和问题参考,相信
Data[T]["items"]和编译器推断的类型是一样的。在这种情况下,类型断言似乎是一个很好的解决方案。关于逻辑运算符,这是漫长的一天,但感谢有关此示例中无关紧要的反馈:) -
this answer 非常详细地介绍了此错误消息。看看吧。
标签: typescript typescript-generics