Typescript类型体操 - AllCombinations

题目

中文

实现类型 AllCombinations<S>,该类型返回字符串 S 中字符的所有排列组合。

English

Implement type AllCombinations<S> that return all combinations of strings which use characters from S at most once.

For example:

type AllCombinations_ABC = AllCombinations<'ABC'>;
// should be '' | 'A' | 'B' | 'C' | 'AB' | 'AC' | 'BA' | 'BC' | 'CA' | 'CB' | 'ABC' | 'ACB' | 'BAC' | 'BCA' | 'CAB' | 'CBA'

答案

/**
 * 将字符 `TChar` 放到字符串 `TStr` 中的任意位置
 * e.g.
 *
 * `Spread<'A', ''>` -> `'A'`
 *
 * `Spread<'A', 'B'>` -> `'AB' | 'BA'`
 *
 * `Spread<'A', 'BC'> `-> `'ABC' | 'BAC' | 'BCA'`
 *
 * `Spread<'A', 'BCD'>` -> `'ABCD' | 'BACD' | 'BCAD' | 'BCDA'`
 */
type Spread<TChar extends string, TStr extends string> =
    | `${TChar}${TStr}`
    | (TStr extends `${infer L}${infer R}`
          ? `${L}${Spread<TChar, `${R}`>}`
          : TChar)
    | `${TStr}${TChar}`;
type AllCombinations<S extends string> = S extends `${infer L}${infer R}`
    ? AllCombinations<R> | `${Spread<L, AllCombinations<R>>}`
    : S;

思路参考了: https://github.com/type-challenges/type-challenges/issues/13509

在线演示

posted @ 2022-10-23 20:21  Laggage  阅读(35)  评论(0编辑  收藏  举报