Closed
Description
🔎 Search Terms
"regexp", "groups", "capture groups"
🕗 Version & Regression Information
- This is the behavior in every version I tried, and I reviewed the FAQ for entries about key types and object types.
- I was unable to test this on prior versions to 4.0.5 because RegExpMatchArray.groups was added then.
⏯ Playground Link
💻 Code
const match = 'a'.match(/(?<letter>[a-z])|(?<number>\d)/);
if (match?.groups) {
const groups = match.groups as { letter: string; number: undefined } | { letter: undefined; number: string }; // can't directly typecast
console.log(groups);
if ('number' in match.groups) console.log(match.groups.number.length); // crashes without warning
}
🙁 Actual behavior
- TypeScript has RegExpMatchArray.groups typed as
{ [key: string]: string }
instead of potentially{ [key: string]: string | undefined }
, and does not allow typecasting it to an object withundefined
as a value.
- TypeScript does not allow casting
Match.groups
as an object whose keys may be undefined (eg:{ group1: string; group2: undefined }
) - TypeScript assumes the
in
operator to narrow the type due toundefined
not being a valid value, despite unmatched named groups in alternation in RegEx returning undefined.
🙂 Expected behavior
undefined
should be allowed in the value type (for typecasting correctly or for correctly not narrowing within
).
Additional information about the issue
Checked #32098 but that looks at inferring types, not allowing casting.
Metadata
Metadata
Assignees
Labels
No labels