Skip to content

Why is MagicRegExpMatchArray typed with string | undefined? #233

Open
@michaelschufi

Description

@michaelschufi

Hi

First, thank you so much for this library. I love it so far. I came across a typing issue while trying it out, and thought I'd report it.

🐛 The bug

const regex = createRegExp(
  anyOf('A', 'B', 'C')
    .groupedAs('opponent')
    .and(' ')
    .and(anyOf('X', 'Y', 'Z').groupedAs('self'))
);

// Results in: /(?<opponent>A|B|C) (?<self>X|Y|Z)/

console.log('A Y'.match(regex)?.groups); // { opponent: 'A', self: 'Y' }
console.log('B '.match(regex)?.groups); // undefined
console.log('C Z'.match(regex)?.groups); // { opponent: 'C', self: 'Z' }

The type of each groups is Record<"opponent" | "self", string | undefined>.

Why is the type in
https://github.com/danielroe/magic-regexp/blob/50ac0caa55e6e3fe2c7397297d8a1533190c5012/src/core/types/magic-regexp.ts#L35

defined as string | undefined?

How can the value of the group be undefined while still matching the reg exp?

🛠️ To reproduce

https://stackblitz.com/edit/github-ppjiny?file=index.ts

🌈 Expected behaviour

The type of each groups should be Record<"opponent" | "self", string>.

ℹ️ Additional context

No response

Metadata

Metadata

Assignees

Labels

bugSomething isn't working

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions