如果 Array.includes() 结果类型是输入对象类型的更严格类型,
它会出错。我该如何处理这个问题?
这是案例的例子。
索引.d.ts
type OddNumberType = 1|3|5|7|9
type AllNumberType = OddNumberType|0|1|...|9
业务逻辑.ts
let targetNumber:AllNumberType = parseInt(Math.random*10)
const oddArray:OddNumberType[] = [1,3,5,7,9]
let resultNumber:OddNumberType = 1;
if(oddArray.includes(targetNumber)){
resultNumber = targetNumber
}
问题
Type 'AllNumberType' is not assignable to type 'OddNumberType'.
Type 2 is not assignable to type 'OddNumberType'.ts(2322)
看来你想使用oddArray.includes
就好像它是一个类型保护它接受任意数字作为其参数,并且如果它返回true
,那么 Typescript 应该将参数的类型缩小为OddNumberType
.
The Array.includes
方法没有像这样声明为类型保护,并且不应该:如果类型保护返回false
这应该意味着论点是not它所保护的类型,但通常如果是某种类型的数组T[]
不包含元素,这并不意味着该元素不是类型T
。你的数组有一些特别之处,这使得它includes
在这种特定情况下,方法是一个明智的类型保护 - 它不仅仅是一个数组OddNumberType
值,它是一个数组every OddNumberType
value.
所以,我们可以声明一个类型ArrayOfEveryOddNumber
这与以下相同OddNumberType[]
但它的includes
方法是类型保护:
type ArrayOfEveryOddNumber = OddNumberType[] & {
includes(arg: AllNumberType): arg is OddNumberType
}
const oddArray = [1, 3, 5, 7, 9] as ArrayOfEveryOddNumber;
请注意,类型断言as ArrayOfEveryOddNumber
也是需要的。
游乐场链接
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)