为什么 VS Code/TypeScript 无法识别 Regex.exec 结果的索引 属性?

Why doesn't VS Code/TypeScript recognize the indices property on the result of Regex.exec?

如果你看这个 exec documentation,它说 属性 应该存在,叫做 indices:

An array where each entry represents a substring match. Each substring match itself is an array where the first entry represents its start index and the second entry its end index. The indices array additionally has a groups property which holds an object of all named capturing groups. The keys are the names of the capturing groups and each value is an array with the first item being the start entry and the second entry being the end index of the capturing group. If the regular expression doesn't contain any capturing groups, groups is undefined.

Here is my code:

  const ex = / ([a-z])/dg.exec(
    "a b c d e f"
  );
  if (ex) {
    const x = ex.indices; // Error! Property 'indices' does not exist on type 'RegExpExecArray'.
  }

我觉得我错过了一些非常明显的东西。为什么不能编译,我该如何编译?

增加.indicies的提议是在TS github上pretty new - it only advanced to Stage 4 in the TC39 process less than a year ago, and TypeScript hasn't integrated it yet. There is an open issue增加.indicies,但还没有修复

简而言之,如果您想让它正常工作,您必须等到有人将此新功能贡献给 TypeScript 类型。

当然,您可以自己定义一个类型,然后使用 as 断言:

type RegExpMatchArrayWithIndices = RegExpMatchArray & { indices: Array<[number, number]> };

const ex = / ([a-z])/dg.exec(
    "a b c d e f"
);
if (ex) {
    const x = (ex as RegExpMatchArrayWithIndices).indices;
}