Skip to content

Inferred types for named capture groups in RegExp #61413

New issue

Have a question about this project? # for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “#”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? # to your account

Closed
6 tasks done
nabeelvalley opened this issue Mar 13, 2025 · 2 comments
Closed
6 tasks done

Inferred types for named capture groups in RegExp #61413

nabeelvalley opened this issue Mar 13, 2025 · 2 comments

Comments

@nabeelvalley
Copy link

nabeelvalley commented Mar 13, 2025

πŸ” Search Terms

regex capture group types inference

βœ… Viability Checklist

⭐ Suggestion

I think it would be useful to have capture groups inside of regexps to be represented in the type of RegExpExecArray.groups

πŸ“ƒ Motivating Example

Given the following RegExp:

const groups = /^(?<initial>\w)\w*/g.exec("Bob").groups

The type of groups should be inferred as:

{
  initial?: string
}

This may imply that the type of RegExp needs to be generic over the named capture groups, so something like this:

const initialRegexp: RegExp<'initial' | 'rest'> = /^(?<initial>\w)(?<rest>\w*)/g

πŸ’» Use Cases

  1. What do you want to use this for? Better type inference when using RegExps
  2. What shortcomings exist with current approaches? All keys of groups are string which can lead to errors if accessing a property that isn't in the RegExp
  3. What workarounds are you using in the meantime? Casting to the expected type
@xiBread
Copy link

xiBread commented Mar 13, 2025

Duplicate of #32098; already being worked on in #60249

@nmain
Copy link

nmain commented Mar 13, 2025

Duplicate of #32098

To help other searchers, this can be found with search terms regex group type

# for free to join this conversation on GitHub. Already have an account? # to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

3 participants