【问题标题】:Can I test a string with regex using io-ts in Typescript我可以在 Typescript 中使用 io-ts 使用正则表达式测试字符串吗
【发布时间】: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


    【解决方案1】:

    正则表达式类型不是 (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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2023-04-10
      • 1970-01-01
      • 2010-09-29
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-19
      • 2014-06-10
      相关资源
      最近更新 更多