Advertisement
Intermediate TypeScript, Conditional Types

How do you prevent a conditional type from distributing over a union?

Short answer

Wrap both sides of 'extends' in a single-element tuple (like [T] extends [U]), which makes T no longer a 'naked' type parameter — this disables the automatic distribution behavior and treats the union as one combined type instead.

Save TypeScript mock interview
Advertisement
AModel answer
Wrap both sides of 'extends' in a single-element tuple (like [T] extends [U]), which makes T no longer a 'naked' type parameter — this disables the automatic distribution behavior and treats the union as one combined type instead.
type IsUnion<T, U = T> = T extends U ? ([U] extends [T] ? false : true) : never;
type ToArrayNonDist<T> = [T] extends [any] ? T[] : never;
type A = ToArrayNonDist<string | number>; // (string | number)[]
Real-world example
Writing a utility type that needs to test a union AS A WHOLE, rather than transforming each member separately.
Likely follow-ups
  • Why does this trick with a wrapping tuple actually work to suppress distribution?
Related topics