【问题标题】:What is the typescript type for the return value of String.prototype.match()?String.prototype.match() 的返回值的打字稿类型是什么?
【发布时间】:2023-01-09 21:25:50
【问题描述】:

我正在用 javascript 写一个正则表达式

const pattern = /S(\d+)E(\d+)/; // get characters inbetween "S" and "D"
const result  = 'SE01E09'.match(pattern);

我如何输入结果变量?

我尝试了几种不同的方法,例如以下无济于事

const result: Array<string | number>  = 'SE01E09'.match(pattern);

【问题讨论】:

  • 推断出类型后,您可以轻松地使用您的 IDE 或 typescriptlang.org/play 来检查实际结果。在这种情况下是const result: RegExpMatchArray | null

标签: javascript regex typescript


【解决方案1】:

它将是 RegExpMatchArray | null

const result: RegExpMatchArray  | null  = 'SE01E09'.match(pattern);

更多详情可参考here

【讨论】:

    【解决方案2】:

    结果变量的类型应为字符串数组。 Array.prototype.match() 方法返回一个数组,第一个元素是整个匹配的字符串,后面是模式中存在的任何捕获组。由于您的模式包含两个捕获组 (d+),因此生成的数组将包含三个元素:整个匹配字符串、第一个捕获组和第二个捕获组。

    以下是键入结果变量的正确方法:

    const result: Array<string>  = 'SE01E09'.match(pattern);
    

    您还可以使用类型别名或元组来指定数组中元素的类型:

    type MatchResult = [string, string, string];
    
    const result: MatchResult = 'SE01E09'.match(pattern);
    
    // or
    
    const result: [string, string, string] = 'SE01E09'.match(pattern);
    

    【讨论】:

      猜你喜欢
      • 2021-12-02
      • 2016-11-06
      • 1970-01-01
      • 2020-06-29
      • 2015-08-10
      • 2017-05-20
      • 2022-12-18
      • 2022-01-19
      • 2019-01-26
      相关资源
      最近更新 更多