Vlad
Vlad

Reputation: 47

How to pick only array types from union type

The question is if it is possible to do something like that:

type a = string[] | number[] | boolean
//here i want to pick only array types from a, to make b: string[] | number[]
type b = a

But it could be of type boolean[] | number[] | string. So that should work dynamically

Upvotes: 0

Views: 647

Answers (2)

dhaker
dhaker

Reputation: 1815

It can be done using generics

type A = string[] | number[] | boolean

type GetArrayTypes<T> = T extends any[] ? T : never;

type b = GetArrayTypes<A>;

Playground link

Upvotes: 0

jcalz
jcalz

Reputation: 328292

Yes, you can use the Extract<T, U> utility type to filter the union T to only those members assignable to U:

type A = string[] | number[] | boolean

type B = Extract<A, any[]>;
// type B = string[] | number[]

Playground link to code

Upvotes: 3

Related Questions