[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>>]
: []
分类:
TypeScript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源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 <🏄/>