If you look this exec
documentation, it says a property should exist called 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.
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'.
}
I kind of feel like I'm missing something really obvious. Why doesn't this compile and how do I get it to?
CodePudding user response:
The proposal that added .indicies
is 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 on the TS github to add .indicies
, but it hasn't been fixed yet.
In short, if you want this to just work, you'll have to wait until someone contributes this new feature to TypeScript typings.
You could, of course, define a type yourself, and use as
to assert:
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;
}