Why are output1 and output2 not both inferred as [number, number, number] in the following code snippets?
Snippet 1 :
type InferTuple1<T> = T extends any[] ? [...T]: never;
const func1 = <T>(t: InferTuple1<T>) => t;
const output1 = func1([1, 2, 3])
Snippet 2
type InferTuple2<T> = T extends any[] ? [...T]: T;
const func2 = <T>(t: InferTuple2<T>) => t;
const output2 = func2([1, 2, 3]);
output1 is inferred as:
const output1: [number, number, number]
output2 is inferred as:
const output2: number[]
I understand the type inference in the first case: the input is an array (extending any[]) so it is inferred as [...T], converting T into a tuple of type [number, number, number]
In the second case, the input is still an array, but it appears that the second conditional branch is executed. I am confused as to why this happens, as I would expect Typescript to return the first one since the condition is met.
(Similarly, func1(["foo", 42, "bar"])
is inferred as [string, number, string]
, while func2(["foo", 42, "bar"])
is inferred as (string | number)[])