【发布时间】:2020-01-29 07:36:36
【问题描述】:
当我使用两个自定义 Typecsipt 类型 'OptionsPostData3 | OptionsPostData4'(临时名称,抱歉)和一个三元运算符时,我收到一条神秘的错误消息,仅使用 OptionsPostData3 或仅 OptionsPostData4 我的代码的一半或另一半没有得到一条错误消息...
我的代码是这样的
const postData: OptionsPostData3 | OptionsPostData4 =
!!optionIds && optionIds.length > 0
? {
optionIds,
}
: {
filters: [
{
underlyingId,
expiryDate,
optionType: optionType || void 0,
minstrikePrice: minstrikePrice || 0,
maxstrikePrice: maxstrikePrice || 0,
},
],
};
我没有幸运地尝试在线找到解决方案,并且在神秘的错误消息中找到解决方案可能很明显(或者可能不是),但我不知道我应该做什么......
类型是这样定义的
export type OptionsPostData3 = {
filters: Filters[];
};
export type OptionsPostData4 = { optionIds: number[] };
export interface OptionsIdArray {
optionIds: number[];
}
export interface FiltersArray {
filters: Filters[];
}
export interface Filters {
underlyingId: number;
expiryDate: string;
optionType: string;
minstrikePrice: number;
maxstrikePrice: number;
}
我认为该错误消息可能提供了足够的信息来解决我的问题,但我没有找到如何...而且我想避免使用 any 类型关键字:
错误信息如下所示
Type '{ optionIds: number[]; } | { filters: { underlyingId: number | undefined; expiryDate: string | undefined; optionType: string | undefined; minstrikePrice: number; maxstrikePrice: number; }[]; }' is not assignable to type 'OptionsPostData4 | OptionsPostData3'.
Type '{ filters: { underlyingId: number | undefined; expiryDate: string | undefined; optionType: string | undefined; minstrikePrice: number; maxstrikePrice: number; }[]; }' is not assignable to type 'OptionsPostData4 | OptionsPostData3'.
Type '{ filters: { underlyingId: number | undefined; expiryDate: string | undefined; optionType: string | undefined; minstrikePrice: number; maxstrikePrice: number; }[]; }' is not assignable to type 'OptionsPostData3'.
Types of property 'filters' are incompatible.
Type '{ underlyingId: number | undefined; expiryDate: string | undefined; optionType: string | undefined; minstrikePrice: number; maxstrikePrice: number; }[]' is not assignable to type 'Filters[]'.
Type '{ underlyingId: number | undefined; expiryDate: string | undefined; optionType: string | undefined; minstrikePrice: number; maxstrikePrice: number; }' is not assignable to type 'Filters'.
Types of property 'underlyingId' are incompatible.
Type 'number | undefined' is not assignable to type 'number'.
Type 'undefined' is not assignable to type 'number'.ts(2322)
如果您需要完整的项目作为参考this is the GitHub link, it starts on line 20
【问题讨论】:
-
你能分享完整的代码吗?
underlyingId和optionIds之类的值设置为什么? -
我在该页面上得到了错误,而无需为
underlyingId as number或optionIds as number[ ]设置或分配任何值 -
检查调用签名,大部分值与
OptionsPostData3中定义的不匹配。 github.com/Luxcium/questrade-ts/blob/… 例如,说underlyingId: number;但签名说它可以是未定义的。尝试分配默认值或放松Filters中的类型以允许undefined、null等 -
@skovy 对我来说奇怪的是,如果我说 const postData: OptionsPostData4 = !!optionIds && optionIds.length > 0` ...第一部分(上半部分)通过或者如果我说` const postData: OptionsPostData3 = !!optionIds && optionIds.length > 0 ` ...最后一部分(后半部分)通过
标签: typescript types interface union