[Typescript] 32. Medium - Permutation

Implement permutation type that transforms union types into the array that includes permutations of unions.

type perm = Permutation<'A' | 'B' | 'C'>; // ['A', 'B', 'C'] | ['A', 'C', 'B'] | ['B', 'A', 'C'] | ['B', 'C', 'A'] | ['C', 'A', 'B'] | ['C', 'B', 'A']

 

Test cases:

/* _____________ Test Cases _____________ */
import type { Equal, Expect } from '@type-challenges/utils'

type cases = [
  Expect<Equal<Permutation<'A'>, ['A']>>,
  Expect<Equal<Permutation<'A' | 'B' | 'C'>, ['A', 'B', 'C'] | ['A', 'C', 'B'] | ['B', 'A', 'C'] | ['B', 'C', 'A'] | ['C', 'A', 'B'] | ['C', 'B', 'A']>>,
  Expect<Equal<Permutation<'B' | 'A' | 'C'>, ['A', 'B', 'C'] | ['A', 'C', 'B'] | ['B', 'A', 'C'] | ['B', 'C', 'A'] | ['C', 'A', 'B'] | ['C', 'B', 'A']>>,
  Expect<Equal<Permutation<boolean>, [false, true] | [true, false]>>,
  Expect<Equal<Permutation<never>, []>>,
]

 

Let's first solve the case:

Expect<Equal<Permutation<never>, []>>

, first idea would be:

type Permutation<T> = T extends never ? [] : [T];
type x = Permutation<never> // x is never

It doesn't work out, something nothing extends never, but if we put never into [never]:

type Permutation<T> = [T] extends [never] ? [] : [T];
type x = Permutation<never> // x is []

 

Then let's see:

Expect<Equal<Permutation<boolean>, [false, true] | [true, false]>>,

, first try

type Permutation<T> = T extends boolean ? T : [];
type x = Permutation<boolean> // x is boolean

But if we put [T]

type Permutation<T> = T extends boolean ? [T] : [];
type x = Permutation<boolean> // x= [false] | [true]

 So, boolean can be infer into false or true, that's great

 

Next step:

type Permutation<T, U = T> = [T] extends [never] 
  ? [] 
  : U extends infer X 
    ? [X]
    : []

type x =Permutation<'A' | 'B' | 'C'> // x = [A] | [B] | [C]

 

Final:

type Permutation<T, U = T> = [T] extends [never] 
  ? [] 
  : U extends infer X 
    ? [X, ...Permutation<Exclude<T, X>>]
    : []

 

posted @ 2022-09-15 01:36  Zhentiw  阅读(29)  评论(0编辑  收藏  举报