带有联合排列但没有重复的打字稿字符串文字

Typescript string literal with permutations of union but no repetitions

我有以下联盟:

type Letter = 'a' | 'b' | 'c' | 'd' | 'e'

我想允许使用模板文字类型排列 1-3 个字母:

type Variation = Letter | `${Letter}-${Letter}` | `${Letter}-${Letter}-${Letter}`

如何在 Typescript 中实现这一点,同时防止重复字母,所以“a”、“b-d”、“a-c-d”和“d-c-a”都可以,但不允许使用“a-a-c”。

type Letter = 'a' | 'b' | 'c' | 'd' | 'e'

type Variation<T> =
    (T extends `${infer A}-${infer B}`
        ? (B extends `${infer BA}-${infer BB}`
            ? (
                `${A}-${Exclude<Letter, A>}-${Exclude<Exclude<Letter, BA>, A>}`
            )
            : (`${A}-${Exclude<Letter, A>}`)
        )
        : T
    );

const a: Variation<'a'> = 'a';
const b: Variation<'a-b'> = 'a-b';
const c: Variation<'a-b-c'> = 'a-b-c';

const d: Variation<'a-b-a'> = 'a-b-a'; // Error
const e: Variation<'a-d-d'> = 'a-d-d'; // Error
const f: Variation<'a-a-a'> = 'a-a-a'; // Error