字符串类型上不存在属性'matchAll'。

55

我想对字符串应用正则表达式。为了获取所有组的结果,我正在使用matchAll方法。这是我的代码

const regexp = RegExp('foo*','g'); 
const str = "table football, foosball";
let matches = str.matchAll(regexp);

for (const match of matches) {
   console.log(match);
}

在编译上面的代码时,我遇到了错误:

类型“"table football, foosball"”上不存在属性“matchAll”。

在搜索这个错误时,我在stackoverflow上找到了类似的问题:

TS2339:类型“string”上不存在属性“includes”

我按照上述链接中提到的更改了tsconfig配置,但我的问题没有解决。

这是我的tsconfig代码:

{
 "compileOnSave": false,
 "compilerOptions": {
 "baseUrl": "./",
 "importHelpers": true,
 "outDir": "./dist/out-tsc",
 "sourceMap": true,
 "declaration": false,
 "module": "es2015",
 "moduleResolution": "node",
 "emitDecoratorMetadata": true,
 "experimentalDecorators": true,
 "target": "es2016",
 "typeRoots": [
  "node_modules/@types"
 ],
"lib": [
  "es2018",
  "dom"
]
}
}
3个回答

79

String.prototype.matchAll()是ECMAScript 2020规范(草案)的一部分。 在TypeScript中,您可以通过添加es2020es2020.string到编译选项中来包含这些库特性:

"compilerOptions": {
    "lib": ["es2020.string"]
}

1
我刚刚添加了这个,因为我遇到了与 OP 相同的问题。但是现在我在命令行控制台中收到以下错误:.matchAll 不是一个函数。你有什么想法是出了什么问题吗? - Andy
2
如果你在运行时遇到了 matchAll is not a function 的错误,这可能是因为你正在使用 TypeScript 作为类型检查器,并且同时使用其他工具(例如 webpack + babel)作为转译器。因此,你仍然需要找到一种方法来填充 matchAll 函数。 - Jay Wick
4
我在jsconfig.json中使用"lib": ["es2020.string"]时遇到了一些非常奇怪的行为。 使用"target": "es2020"效果更好。 此外,不知何故,尽管vsc声称正在运行v15,但必须在launch.json中更改节点版本,因为节点没有matchAll。 - Tamir Daniely
1
将目标更改为es2020对我解决了问题。谢谢。 - ufk

3

检查 StringRegExp 类的 ts 签名时,我意识到没有 matchAll 的签名。解决它的一种方式可能是:

let matches = str['matchAll'](regexp);

另一种方法是将该方法添加到lib.es5.d.ts文件中 enter image description here


这段代码在这里是如何工作的 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/String/match - Yousuf
谢谢@SergioEscudero,我已经检查了你的第一个建议,它像预期的那样工作得很好,但奇怪的是它在Chrome浏览器上运行良好,但在Firefox上会抛出错误“str.matchAll不是一个函数”。我会检查你的第二个建议。 - Yousuf
检查浏览器兼容性 https://developer.mozilla.org/zh-CN/docs/Web/JavaScript/Reference/Global_Objects/RegExp/@@matchAll#Browser_compatibility - Sergio Escudero
str'matchAll' 的解决方法会出现错误,因为索引表达式不是数字类型。如果 Str 是一个字符串,那么 str[x] 不应该期望一个数值索引吗? - GGizmos

1

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接