I have the following definition:
function foo(arg: number[] | number) {
if (Array.isArray(arg)) {
return [1]
}
return 0
}
I would expect typescript to figure out automatically what the return type is. Because of the type guard isArray()
it knows if arg is an Array and can show the return type as number[]
. However, using foo(...)
shows its return value as number[] | 0
even when passing an array.
foo([]).push() // error because push doesnt exist on type 0
Is this a design limitation, a bug, just not implemented yet, or some other issue?
I can't point to something definitively saying it's a design limitation, but I've seen experts like jcalz and Titian Cernicova-Dragomir citing various places where type inference is limited sometimes not because it couldn't do what we want, but because it would be too costly to do it (in terms of runtime cost or code complexity in the compiler). I suspect this fits into that category.
You probably know this, but for your specific example, you can use overloads to get the result you want:
function foo(arg: number[]): number[];
function foo(arg: number): number;
function foo(arg: number[] | number) {
if (Array.isArray(arg)) {
return arg.map(v => v * 2);
}
return arg * 2;
}
foo([]).push(10);
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments