Skip to content

This notebook belongs to

Sadat Jubayer

Senior Software Engineer at Premio

If found, please return to hello@jubayer.dev

Vol. 7Seven years of building

Started
January 2020
Everyday tools
TypeScript, Vue, React, Next.js, NestJS, React Native
Education
B.Sc. CSSE, AIUB, 2020
2 min readTypeScript

Stop unions splitting in conditional types

Wrap both sides of a conditional type in tuples to check a union as a whole.

You wrote a type that turns T into an array of T, passed it string | number, and expected (string | number)[]. A mixed array is rejected, and the error mentions string[] and number[] as two options.

type ToArray<T> = T extends unknown ? T[] : never

const split: ToArray<string | number> = [1, 'a']
// error TS2322: Type '(string | number)[]' is not assignable to type 'string[] | number[]'.

The result is string[] | number[]: a type that requires the array to fit one of its two member types.

Why the union splits

A conditional type whose checked type is a bare type parameter applies to each union member on its own and joins the results. These are called distributive conditional types. ToArray<string | number> becomes ToArray<string> | ToArray<number>, which is string[] | number[].

diagram

ToArray splits the union, ToArrayWrapped does not

The bare parameter splits the union into members. The tuple-wrapped version checks the union as a whole.

Wrap both sides in a tuple

The split only happens when T stands alone on the left of extends. Put it inside a one-element tuple, on both sides, and the check runs once on the whole union.

type ToArrayWrapped<T> = [T] extends [unknown] ? T[] : never

const whole: ToArrayWrapped<string | number> = [1, 'a']

This compiles because the result is (string | number)[], which accepts a mix of strings and numbers.

The same trap shows up in yes or no questions. Here the bare version runs twice, and the wrapped one asks about the union as a whole.

type IsString<T> = T extends string ? true : false
type IsOnlyString<T> = [T] extends [string] ? true : false

const a: IsString<string | number> = 'probe'
// error TS2322: Type 'string' is not assignable to type 'boolean'.
const b: IsOnlyString<string | number> = 'probe'
// error TS2322: Type '"probe"' is not assignable to type 'false'.

IsString is boolean because string gave true, number gave false, and the two were joined. IsOnlyString is false: [string | number] is not assignable to [string], so the false branch runs once.

I wrap when I want one answer for the union as a whole. I leave the bare form when I want member-by-member behaviour, which is how Exclude works: Exclude<'a' | 'b', 'a'> is 'b'.