Below, in this demonstration (linked playground, I anticipate that Foo<[0, 1]>
and Bar<[0, 1]>
will both be resolved to 0[] | 1[]
due to the distribution of unions in conditional types. However, in actuality, Foo<[0, 1]>
ends up being (0 | 1)[]
and the compiler indicates that the first @ts-expect-error
directive is unused.
type Foo<T extends ArrayLike<unknown>> = T[number] extends infer Elem
? Elem[]
: never;
type Bar<T extends ArrayLike<unknown>> = T[number] extends infer Elem
? Elem extends infer U
? U[]
: never
: never;
// @ts-expect-error
const foo: Foo<[0, 1]> = [0, 1];
// @ts-expect-error
const bar: Bar<[0, 1]> = [0, 1];
Upon reviewing the documentation, I came across this specific statement;
When conditional types interact with a general type, they become distributive when a union type is involved. (emphasis on "a generic type" mine)
The only explanation I can think of is that in the example, Elem
is a generic type, while T[number]
is not. My assumption is that this leads to the conditional type not distributing with T[number]
, but I am uncertain about the accuracy of my conclusion. Can anyone clarify this behavior?