【发布时间】:2021-06-03 18:12:21
【问题描述】:
const a = "test-string";
const regex = new RegExp(/^t*/);
regex.test(a);
io-ts 中是否有对应的 regex.test(a) 将在运行时检查错误?
【问题讨论】:
标签: javascript regex typescript types
const a = "test-string";
const regex = new RegExp(/^t*/);
regex.test(a);
io-ts 中是否有对应的 regex.test(a) 将在运行时检查错误?
【问题讨论】:
标签: javascript regex typescript types
正则表达式类型不是 (yet?) Typescript 的一部分,因此 io-ts 可能无法为您提供帮助。
但是,您可以使用 template strings from Typescript 4.1 来获得类似的东西。
type T = "test-string";
const a = "test-string";
type Test1 = typeof a extends T ? true : false;
// type Test1 = true
const b = "something-different";
type Test2 = typeof b extends T ? true : false;
// type Test2 = false
如果你想匹配字符串的子集,你需要分步执行:
type T = "papaya";
const a = "mango papaya pineapple";
type Test = typeof a extends `${infer head}${T}${infer tail}` ? true : false;
// type Test = true;
这是一个非常简化的示例 - 这是一个非常强大的功能。上面的链接有更多的例子,the original PR
【讨论】: