5

I have a conditional type that uses a generic type T to determine an Array<T> type. As a contrived example:

type X<T> = T extends string ? Array<T> : never;

The issue I am having is when I provide a union type, it is being distributed as a union of 2 array types instead of an array of my union type.

// compiler complains because it expects Array<'one'> | Array<'two'>
const y: X<'one' | 'two'> = ['one', 'two'];

Is there a way to type this such that my conditional type produces an Array<'one' | 'two'> if the condition is met?

bingles
  • 11,582
  • 10
  • 82
  • 93

1 Answers1

13

You have run into the distributive behavior of conditional types where a conditional type is distributed over a naked type parameter containing a union. This behavior is very useful in some scenarios but can be a bit surprising at first.

The simples option to disable this behavior is to put the type parameter in a tuple:

type X<T> = [T] extends [string] ? Array<T> : never;

// ok y is Array<'one' | 'two'>
const y: X<'one' | 'two'> = ['one', 'two'];

You can read more about this behavior here and here

Claude
  • 8,806
  • 4
  • 41
  • 56
Titian Cernicova-Dragomir
  • 230,986
  • 31
  • 415
  • 357