Skip to content

Inferred types for named capture groups in RegExpΒ #61413

Closed
@nabeelvalley

Description

@nabeelvalley

πŸ” 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

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions