9

I'm getting Property 'groups' does not exist on type 'RegExpExecArray' when trying

const r = /\w+, (?<foo>\w+)/
const m = r.exec('hello, world')

if (m) {
    const groups = m.groups
}

Javascript has an option to call .groups on a regex exec result. And I know the output is actually an array... but grabbing a specific index to get the groups seems a bit hacky. Is pulling from the list the only option in Typescript?

Wompinalong
  • 143
  • 1
  • 8
  • Have you tried: m[1] ? – Poul Bak Oct 23 '18 at 17:13
  • Hmm, forgot about the ordering of the array... should be alright in this scenario. But what if you wanted access to the key-value version FeelsBadMan – Wompinalong Oct 23 '18 at 17:26
  • 5
    This has been incorrectly flagged as a duplicate of the related JS question. `RegExpExecArray` is missing a type definition for the `groups` property in TS. – Keith Jan 07 '19 at 08:22
  • 1
    @Keith is right. I know "groups" property is optional and it might be understandable not to add it to `RegExpMatchArray`, but since it's an `Array`, if I use `m["groups"]` TS generates error `Element implicitly has an 'any' type because index expression is not of type 'number'.` And if I use `m.groups`, then I got `Property 'groups' does not exist on type 'RegExpMatchArray'.` – soundlake Apr 23 '19 at 06:31
  • Apparently, it's already reported and fixed in typescript 2.8 (https://github.com/Microsoft/TypeScript/issues/22082). – soundlake Apr 23 '19 at 06:41

1 Answers1

4

m[1] will bring "world".

You can access groups as m['groups'].

if (m) {
 const groups = m['groups'];
}

because if you console.log / debug at m you can see, groups is an object from the result. Above mentioned is a more specific way to access an object if you know the property name.

reddevilzee
  • 93
  • 1
  • 6