属性“ matchAll”在“字符串”类型上不存在

You*_*suf 13 typescript angular7

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

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

for (const match of matches) {
   console.log(match);
}
Run Code Online (Sandbox Code Playgroud)

在上面的代码编译期间,我得到了错误

类型““桌上足球,桌上足球”上不存在属性'matchAll'

在搜索此错误期间,我在stackoverflow上发现了类似的问题

TS2339:类型“字符串”上不存在属性“包含”

我按上面链接中所述更改了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"
]
}
}
Run Code Online (Sandbox Code Playgroud)

小智 14

String.prototype.matchAll()是ECMAScript 2020规范(草稿)的一部分。在TypeScript中,可以通过在编译器选项中添加es2020或来包括这些库功能es2020.string

"compilerOptions": {
    "lib": ["es2020.string"]
}
Run Code Online (Sandbox Code Playgroud)

  • 我在 jsconfig.json 中使用 `"lib": ["es2020.string"]` 得到了一些非常奇怪的行为。使用 `"target": "es2020"` 效果更好。还必须更改 launch.json 中的节点版本,由于某种原因,即使 vsc 声称它正在运行 v15,节点也没有 matchAll,不知道这是如何发生的。 (4认同)
  • 如果您收到“matchAll is not a function”作为运行时错误,这可能是因为您使用 typescript 作为类型检查器并使用其他东西(例如 webpack + babel)作为转译器。因此,您仍然需要找到一种方法来使用 polyfil matchAll 函数 (2认同)