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?

5
  • Have you tried: m[1] ? Commented Oct 23, 2018 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 Commented Oct 23, 2018 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. Commented Jan 7, 2019 at 8: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'. Commented Apr 23, 2019 at 6:31
  • Apparently, it's already reported and fixed in typescript 2.8 (github.com/Microsoft/TypeScript/issues/22082). Commented Apr 23, 2019 at 6:41

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.