-
-
Notifications
You must be signed in to change notification settings - Fork 52
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Why is MagicRegExpMatchArray
typed with string | undefined
?
#233
Comments
string | undefined
?MagicRegExpMatchArray
typed with string | undefined
?
Hi @michaelschufi, I think the behavior you're observing is actually working as intended. We didn't touch any runtime logic (helpers are transform to pure RegExp), so it behave exactly as native RegExp at runtime. The issue here is that console.log('B '.match(/(?<opponent>A|B|C) (?<self>X|Y|Z)/)?.groups);
// return `undefined` maybe what you want/expect is making the const regex = createRegExp(
anyOf('A', 'B', 'C')
.groupedAs('opponent')
.and(' ')
.and(anyOf('X', 'Y', 'Z').groupedAs('self').optionally())
); this resolve to console.log('B '.match(/(?<opponent>A|B|C) (?<self>X|Y|Z)?/)?.groups)
// return `{ opponent: 'B', self: undefined }` this is why the type of groups is Record<"opponent" | "self", string | undefined>, as we can still match a certain RegExp but not all of the groups having captured values. Please let me know if you have any further questions or concerns. Thank you! |
Thank you for the fast response. The first part, I completely agree with. Since Regarding the second case, you hit the nail on the head. I expect the value part of the type to be Edit: In the meantime I've started to write an enhancement request issue regarding the type resolution for the groups. It would be awesome if the type of each group could be inferred based on the |
Hi @michaelschufi, Yes, you are right. If all the groups are not optional, the match result should either be I've benn working on a new type inferrencing for a while, I've put more detail at #235, hopefully will resolve this and many other cases 👍 |
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
The type of each
groups
isRecord<"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 beRecord<"opponent" | "self", string>
.ℹ️ Additional context
No response
The text was updated successfully, but these errors were encountered: