[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>>]
    : []

 

原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/289581.html

(0)
上一篇 2022年9月15日
下一篇 2022年9月15日

相关推荐

发表回复

登录后才能评论