标签:Typescript false 32 never Medium extends Expect Permutation type
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,false,32,never,Medium,extends,Expect,Permutation,type 来源: https://www.cnblogs.com/Answer1215/p/16695171.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。