Daniel Birowsky Popeski
Daniel Birowsky Popeski

Reputation: 9266

How to map Union type to Tuple of the same length?

I want to turn this:

type UnionType = Variant1 | Variant2

into this:

type ResultingType = [UnionType, UnionType]

If the union has 3 member types, the tuple should have 3 elements.

Upvotes: 0

Views: 365

Answers (1)

Guirotar Lionad
Guirotar Lionad

Reputation: 59

Do you mean "permutation"?

type UnionType = 'a' | 'b'

type UnionPermutation<U, K = U> =
  [U] extends [never]
  ? []
  : U extends any
  ? [U, ...UnionPermutation<Exclude<K, U>>]
  : never

// ['a', 'b'] | ['b', 'a']
type test = UnionPermutation<UnionType>

TypeScript Playground

Upvotes: 2

Related Questions