我有一个看起来像这样的类型:
type Location=`${number},${number};${number},${number};...`
是否有像 Repeat<T>
这样的实用程序类型?那可以为我做这个吗?像这样:
type Location=Repeat<`${number},${number};`>
最佳答案
我认为没有一种方法可以为您在变量声明中使用的类型定义无限重复模式。
但是,函数上的类型保护可以检查字符串是否与无限模式匹配,如下所示(playground):
type MatchesPattern<Pattern extends string, Current extends string> = Current extends `` ? string : (Current extends `${Pattern}${infer Rest}` ? MatchesPattern<Pattern, Rest> : never);
type LocationPattern = `${number},${number};`;
declare function onlyAcceptsLocation<L extends string & IsLocation, IsLocation = MatchesPattern<LocationPattern, L>>(location: L): void;
onlyAcceptsLocation("12,34;56,78;"); // 👍 matches
onlyAcceptsLocation("12,34;56,78"); // ⚠️
onlyAcceptsLocation("12'34;56,78;"); // ⚠️
onlyAcceptsLocation("1,2,3;45,67;"); // ⚠️
关于javascript - 如何定义具有重复结构的 typescript 类型?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/70718896/