javascript - 如何定义具有重复结构的 typescript 类型?

标签 javascript typescript

我有一个看起来像这样的类型:

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/

相关文章:

javascript - 浏览器中的 Google Chart 高 RAM

Angular 库未构建为 es5 目标

javascript - NodeJS 需要一个文件中的所有模块,好的做法?

javascript - 如何检查在动态创建的表单行中是否选择了相同的选项

javascript - 使用 bootstrapvalidator AJAX submitHandler 不起作用

javascript - 让 Meteor、Webstorm 和 Typescript 协同工作的最佳实践是什么?

javascript - 带有 typescript 的 AngularJS : this resolved differently in service and config constructor

javascript - 这些函数将以什么顺序执行?

带有 ngx-translate 的 Angular + Electron

node.js - Typescript Express 请求输入