【问题标题】: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);
【问题讨论】:
标签:
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);