boolean[] in conditional types expands to true[] | false[]

Viewed 168

This conditional type tries to make the type argument U into an array:

type MakeArray<U> = U extends boolean ? Array<U> : U;

However, when passed boolean:

type T5 = MakeArray<boolean>;

The result is type T5 = true[] | false[].

I've seen https://github.com/microsoft/TypeScript/issues/30029 but that seems to deal with promises/return values and was in theory fixed in TS 3.5.

I.e. AFAICT that issue is about primitives and distributing over unions, but I'm explicitly checking against extends boolean and not something like extends boolean | number | string.

2 Answers

The answer is probably a bit late but it works by infering the type argument if an array like this

type MakeArray<T, V = T> = T extends Array<infer V> ? T : Array<V>;

type TBoolean = MakeArray<boolean>; // boolean[]
type TBooleanArray = MakeArray<Array<boolean>>; // boolean[]

type TString = MakeArray<string>; // string[]
type TStringArray = MakeArray<Array<string>>; // string[]
Related