【发布时间】:2021-02-04 17:55:01
【问题描述】:
我在联合类型方面有点挣扎,我想知道打字稿是否可以在没有额外检查的情况下推断出值。假设我有这个接口设置(为简洁起见省略了 IBaseDiscount),其中值可以不同,但嵌套的折扣类型名称是固定的
interface IFlatDiscount extends IBaseDiscount {
value:{ formatted: string; value: number };
discountType: {
name: DiscountType.flat;
id: number;
};
}
interface IOpenDiscount extends IBaseDiscount {
value?: number;
discountType: {
name: DiscountType.open;
id: number;
};
}
export interface IPercentageDiscount extends IBaseDiscount {
value: number;
discountType: {
name: DiscountType.percentage;
id: number;
};
}
export type IDiscount = IOpenDiscount | IPercentageDiscount | IFlatDiscount;
现在在我的代码中,当我尝试使用这些值时,我最终不得不执行以下操作
if (discount.discountType.name === DiscountType.flat && typeof discount.value === 'object) {
// now my value is properly typed -- if I leave out the object check it doesnt know the correct type for the value
}
打字稿是否有适当的方法根据 discountType.name 推断值,而不是在任何地方对值进行所有检查?
【问题讨论】:
-
你想要一个discriminated union。然后你可以在判别式上使用 switch 语句。
-
我知道它适用于顶级属性——但它可以从这样的嵌套值中推断出来吗?
-
IDK,有什么特殊的原因你不能扁平化接口的结构或添加顶级判别式吗?
-
我的意思是技术上是的,但这是 API 返回的形状,需要发回,所以我不想更改它。只是看看我是否可以删除额外的值检查
-
除非我做错了什么,apparently it can't narrow the type
标签: typescript