Search code examples
typescriptdiscriminated-union

TypeScript: Conditional type array of union type distribution


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?


Solution

  • 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