[英]Typescript narrowing down within union of tuples
Say I have a function like this:假设我有一个像这样的 function:
function foo(n: number): [number, undefined] | [undefined, number] {
if (n % 2 === 0) {
return [n, undefined];
}
return [undefined, n];
}
And then calling this function like this:然后像这样调用这个 function :
function bar() {
const [a, b] = foo(2);
if (a === undefined) {
return b; // TypeScript infers b as number | undefined
}
return a; // TypeScript infers a as number (good!)
}
Because function foo returns either tuple (number, undefined)
or (undefined, number)
, after not passing the a === undefined
check, TypeScript is able to infer that the type of a
is number when returning it.因为 function foo 返回元组
(number, undefined)
或(undefined, number)
,在没有通过a === undefined
检查后,TypeScript 能够在返回时推断a
的类型是数字。
And within the if
block, because a
is undefined we (humans) can infer the return type of foo here as [undefined, number]
hence, type of b
as number.在
if
块中,因为a
是未定义的,我们(人类)可以将 foo 的返回类型推断为[undefined, number]
因此, b
的类型为 number。 However TypeScript doesn't seem intelligent enough to be able to tell this and reports that it's number | undefined
然而 TypeScript 似乎不够聪明,无法分辨这一点,并报告说它是
number | undefined
number | undefined
. number | undefined
。
Is there a workaround for narrowing down on union of tuples?是否有缩小元组联合范围的解决方法?
TypeScript's discriminating unions don't keep track of the dependency between a
and b
, so after you deconstruct the array, narrowing a
won't affect the type of b
. TypeScript 的区分联合不会跟踪
a
和b
之间的依赖关系,因此在您解构数组后,缩小a
不会影响b
的类型。 To still achieve the desired narrowing, you can directly test the array element, like this:要仍然实现所需的缩小,您可以直接测试数组元素,如下所示:
function bar() {
const arr = foo(2);
if (arr[0] === undefined) {
const b = arr[1]
return b; // TypeScript infers b as number (good!)
}
const a = arr[0]
return a; // TypeScript infers a as number (good!)
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.