如何解决是否可以在 TypeScript 中使用模板文字生成字符串文字组合?
是否可以在 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'
解决方法
你可以让编译器计算这样的排列,尽管排列的数量随着元素的数量呈指数增长,你应该小心使用它。以下是我的处理方式:
type Permutations<T extends string,U extends string = T> =
T extends any ? (T | `${T} ${Permutations<Exclude<U,T>>}`) : never;
然后你想要的类型是传递Permutations
你想要置换的字符串的union:
type ModiferKeyCombinations = Permutations<MetaKey | CtrlKey | ShiftKey | AltKey>;
您可以通过使用该类型和从您的问题手动创建的类型多次声明 var
来验证它们是相同的类型,并看到编译器对此感到满意:
var x: ModiferKeyCombinations;
var x: ManualModiferKeyCombinations; // no compiler error
Permutations<T>
的工作方式:首先,我必须给它两次完整的联合;一次作为 T
参数,一次作为 U
参数。那是因为我们需要在维护它的同时将这个联合拆分为多个部分,以便我们可以使用 the Exclude
utility type 删除一个元素。这个想法是获取完整联合 T
的每一部分 U
,然后单独返回该部分,并使用 template literal string types
Permutations<Exclude<U,T>>
连接到末尾
如果您在 Permutations<T>
为 T
(表示零字符串)时调用 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"
。
...等等;我会停在那里。
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。