In the following snippets, why output1 and output2 are not both inferred as [number, number, number]?
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[]
-
The type inference in the first case is clear to me : the input is an array (so it extends any[])
then it is inferred as […T], which converts T into a tuple of type [number, number, number] -
In the second case, the input is still an array, but it seems that it is the second conditional branch
which is executed, I don’t understand why (I would expect Typescript to return the first one, since the condition is verified).
(in the same fashion func1(["foo", 42, "bar"])
is inferred as [string, number, string]
, whereas func2(["foo", 42, "bar"])
is inferred as (string | number)[])