Skip to content

RegExMatchArray.groups does not allow an undefined value #61476

Closed
@PartMan7

Description

@PartMan7

🔎 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

https://www.typescriptlang.org/play/?target=99&ts=5.9.0-dev.20250324#code/MYewdgzgLgBAtgQysAFjAvDA5ArA6RZFACgHpiB+AHgBsBTKKOgJwD4BtBAWgC8BdAJQAfSlTABXOACMWrADoATAaQEBuAFABLAGYxihVBTwBzZiHEAHCAJgBvdTEcxQkWKfNWM8JKhNnLEDAIgbYw9IwsAFww0MyaYMaqMBLSUTDiYAp02vF0CjAAvjBCdmEMTMzRGVk5YHlJKTKVMVBxCYVJpKTOCGBYsAqazHTAUDQAnjBQ4xYjwVAOTi4QIPR4NCDGxO4BaouOOnpYjSxYMPHeRH4e1s7gK2sbWwYo1wF4J8zrdAlQKGowLrOZjBFB0CDqApAA

💻 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 with undefined 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 to undefined 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 with in).

Additional information about the issue

Checked #32098 but that looks at inferring types, not allowing casting.

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