Skip to content

Navigation Menu

Sign in
Appearance settings

Search code, repositories, users, issues, pull requests...

Provide feedback

We read every piece of feedback, and take your input very seriously.

Saved searches

Use saved searches to filter your results more quickly

Appearance settings

Inferred types for named capture groups in RegExpΒ #61413

Copy link
Copy link
@nabeelvalley

Description

@nabeelvalley
Issue body actions

πŸ” 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
Reactions are currently unavailable

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type
    No fields configured for issues without a type.

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions

      Morty Proxy This is a proxified and sanitized view of the page, visit original site.