[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 @   Zhentiw  阅读(32)  评论(0编辑  收藏  举报
相关博文:
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
历史上的今天:
2020-09-15 [CSS3] Use CSS Variables to Maintain the Aspect Ratio for an Element
2020-09-15 [GraphQL] Multi Query and Alias
2020-09-15 [Machine Learning] Gradient Checking
2019-09-15 [ARIA] What is Accessible Name Calculation?
2019-09-15 [ARIA] Accessible animations with reduced motion
2019-09-15 [ARIA] Accessible modal dialogs
2018-09-15 [Tools] Scroll, Zoom, and Highlight code in a mdx-deck slide presentation with Code Surfer <🏄/>
点击右上角即可分享
微信分享提示