Advertisement
Intermediate TypeScript, Conditional Types

How do distributive conditional types behave when T is a union type?

Short answer

When the checked type T is a naked type parameter (not wrapped in something like [T]) and you pass a union as T, the conditional type automatically distributes over each member of the union individually, then unions the results back together.

Save TypeScript mock interview
Advertisement
AModel answer
When the checked type T is a naked type parameter (not wrapped in something like [T]) and you pass a union as T, the conditional type automatically distributes over each member of the union individually, then unions the results back together.
type ToArray<T> = T extends any ? T[] : never;
type A = ToArray<string | number>; // string[] | number[], NOT (string | number)[]
Real-world example
Understanding why a conditional type applied to a union produces a union of individually-transformed results, which can be surprising at first.
Likely follow-ups
  • How would you prevent distribution and force the union to be treated as a single type?
Related topics