Closed
Description
π Search Terms
regex capture group types inference
β Viability Checklist
- This wouldn't be a breaking change in existing TypeScript/JavaScript code
- This wouldn't change the runtime behavior of existing JavaScript code
- This could be implemented without emitting different JS based on the types of the expressions
- This isn't a runtime feature (e.g. library functionality, non-ECMAScript syntax with JavaScript output, new syntax sugar for JS, etc.)
- This isn't a request to add a new utility type: https://github.com/microsoft/TypeScript/wiki/No-New-Utility-Types
- This feature would agree with the rest of our Design Goals: https://github.com/Microsoft/TypeScript/wiki/TypeScript-Design-Goals
β 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
- What do you want to use this for? Better type inference when using RegExps
- What shortcomings exist with current approaches? All keys of
groups
arestring
which can lead to errors if accessing a property that isn't in the RegExp - What workarounds are you using in the meantime? Casting to the expected type
Metadata
Metadata
Assignees
Labels
No labels