在TypeScript中可以生成字符串文字和模板文字组合的排列吗?
type MetaKey = 'meta';
type CtrlKey = 'ctrl';
type ShiftKey = 'shift';
type AltKey = 'alt';
type ModiferKeyCombinations = ???
其中ModiferKeyCombinations
预期为:
type ModiferKeyCombinations =
| 'meta'
| 'ctrl'
| 'shift'
| 'alt'
| 'meta ctrl'
| 'meta shift'
| 'meta alt'
| 'ctrl meta'
| 'ctrl shift'
| 'ctrl alt'
| 'shift meta'
| 'shift ctrl'
| 'shift alt'
| 'alt meta'
| 'alt ctrl'
| 'alt shift'
| 'meta ctrl shift'
| 'meta ctrl alt'
| 'meta shift ctrl'
| 'meta shift alt'
| 'meta alt ctrl'
| 'meta alt shift'
| 'ctrl meta shift'
| 'ctrl meta alt'
| 'ctrl shift meta'
| 'ctrl shift alt'
| 'ctrl alt meta'
| 'ctrl alt shift'
| 'shift meta ctrl'
| 'shift meta alt'
| 'shift ctrl meta'
| 'shift ctrl alt'
| 'shift alt meta'
| 'shift alt ctrl'
| 'alt meta ctrl'
| 'alt meta shift'
| 'alt ctrl meta'
| 'alt ctrl shift'
| 'alt shift meta'
| 'alt shift ctrl'
| 'meta ctrl shift alt'
| 'meta ctrl alt shift'
| 'meta shift ctrl alt'
| 'meta shift alt ctrl'
| 'meta alt ctrl shift'
| 'meta alt shift ctrl'
| 'ctrl meta shift alt'
| 'ctrl meta alt shift'
| 'ctrl shift meta alt'
| 'ctrl shift alt meta'
| 'ctrl alt meta shift'
| 'ctrl alt shift meta'
| 'shift meta ctrl alt'
| 'shift meta alt ctrl'
| 'shift ctrl meta alt'
| 'shift ctrl alt meta'
| 'shift alt meta ctrl'
| 'shift alt ctrl meta'
| 'alt meta ctrl shift'
| 'alt meta shift ctrl'
| 'alt ctrl meta shift'
| 'alt ctrl shift meta'
| 'alt shift meta ctrl'
| 'alt shift ctrl meta'
发布于 2021-07-05 13:14:31
您可以让编译器计算这样的排列,尽管由于排列的数量随元素的数量呈指数增长,所以您应该小心使用它。下面是我要做的事情:
type Permutations<T extends string, U extends string = T> =
T extends any ? (T | `${T} ${Permutations<Exclude<U, T>>}`) : never;
然后,您想要传递的类型是将Permutations
传递给您想要更改的字符串的友联市:
type ModiferKeyCombinations = Permutations<MetaKey | CtrlKey | ShiftKey | AltKey>;
您可以通过使用该类型和从您的问题手工创建的类型多次声明var
来验证它们是同一类型,并看到编译器对此很满意:
var x: ModiferKeyCombinations;
var x: ManualModiferKeyCombinations; // no compiler error
Permutations<T>
的工作方式:首先,我必须给它两次完整的联合;一次作为T
参数,一次作为U
参数。这是因为我们需要将这个联合分解成它的碎片,同时也要维护它,这样我们就可以用实用程序类型删除一个元素。其想法是获取完整的联合T
的每个U
,然后单独返回该片段,并使用模板文字字符串类型将Permutations<Exclude<U, T>>
连接到最后。
如果在Permutations<T>
是never
(即零字符串)时调用never
,则会得到never
。
如果您调用Permutations<T>
时,T
是一个字符串,如"oneString"
,则使用Permutations<never>
作为回答的一部分:"oneString" | `oneString ${never}`
.根据模板文本字符串的规则,后者只是never
本身。所以只要"oneString"
。
如果您在Permutations<T>
是两个字符串的联合时调用T
,比如"a" | "b"
,那么您可以使用Permutations<"a">
和Permutations<"b">
作为答案的一部分:"a" | `a ${Permutations<"b">}` | "b" | `b ${Permutations<"a">}`
,它变成了"a" | "a b" | "b" | "b a"
。
...and等,我就在那儿停下来。
https://stackoverflow.com/questions/68252446
复制相似问题