Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 456
bingles Avatar asked Jan 01 '19 15:01

bingles


Video Answer


1 Answers

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

like image 65
Titian Cernicova-Dragomir Avatar answered Sep 28 '22 03:09

Titian Cernicova-Dragomir