Skip to content

Infer the literals used in the type of the groups #235

@michaelschufi

Description

@michaelschufi

🆒 Your use case

When I create a regexp group using anyOf and groupedAs, the type of the matched group should be inferred based on the inputs to anyOf.

Similar to the type of the main regexp that gets inferred.

E.g.

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

Here, the type of regex is

MagicRegExp<"/(?<opponent>A|B|C) (?<self>X|Y|Z)/", "opponent" | "self", ["(?<opponent>A|B|C)", ...any[]], never>

so the information that the groups have literals of ABC and XYZ respectively is included in the type. However, the type of

"A Y".match(regex)?.groups.opponent

is string | undefined instead of "A" | "B" | "C".

🔍 Alternatives you've considered

No response

ℹ️ Additional info

My goal is to use this library in conjunction with colinhacks/zod. magic-regexp complements zod well when it comes to string validation and parsing while still being typesafe.

I'm open to work on this myself. Please let me know where I should have a look to get started with such a feature.

Metadata

Metadata

Labels

enhancementNew feature or request

Type

No type

Projects

No projects

Milestone

No milestone

Relationships

None yet

Development

No branches or pull requests

Issue actions