Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

Here is my code:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

  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?

>Solution :

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;
}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading