【发布时间】:2021-09-29 03:27:46
【问题描述】:
我有一个 'Food' 对象,它可以是多种类型,具体取决于 'category' 属性的值。对象来自一个json,所以不可能知道之前的类型。
我正在尝试在 category 属性上使用 switch 语句,以便将 Food 对象转换为正确的类型
export type Category = 'fruit' | 'grain' | 'meat'
interface Food<IngredientCategory extends Category> {
name: string;
category: IngredientCategory
[key: string]: string;
}
interface Fruit extends Food<'fruit'> {
color: string;
}
interface Grain extends Food<'grain'>{
size: string;
}
interface Meat extends Food<'meat'> {
temperature: string
}
type FoodFromCategory<IngredientCategory extends Category> = IngredientCategory extends 'fruit' ? Fruit : IngredientCategory extends 'grain' ? Grain : Meat;
const castFood = <IngredientCategory extends Category>(category: IngredientCategory, food: Food<any>):
Food<IngredientCategory> | undefined => {
switch (category) {
case "fruit":
return food as Fruit
case "grain":
return food as Grain
case "meat":
return food as Meat
}
return undefined
};
这会在返回的行上产生错误:
TS2322:“水果”类型不能分配给“食物”类型。属性“类别”的类型不兼容。类型“水果”不能分配给类型“IngredientCategory”。 “fruit”可以分配给“IngredientCategory”类型的约束,但“IngredientCategory”可以用约束“Category”的不同子类型来实例化。
为什么 switch 语句不缩小“IngredientCategory”通用参数的范围?有没有其他方法可以做到这一点?
【问题讨论】:
-
因为
Fruit不是Food<IngredientCategory>的子类型,所以不能赋值 -
你想做的是上演员。这行不通。基本接口“食物”的返回将起作用。然后稍后使用“类别”来区分它们。
-
您的意思是在某处使用
FoodFromCategory吗?因为你现在不是。
标签: typescript