Introducing ArkRegex
A drop-in replacement for new RegExp() with types
Regular expressions are ubiquitous in modern code.
A few characters sprinkled into your JavaScript can validate and parse strings that would require dozens of lines of imperative logic.
However, that concision comes at a cost. Complex expressions can be hard to understand and type safety is a pipe dream- or at least, it was.
Introducing arkregex, a type-safe wrapper of new RegExp().
The regex function creates a Regex instance with types for .test(), .exec() and more, statically parsed from native JS syntax:
All you need to get started is pnpm install arkregex (or the equivalent for your package manager of choice) đ
Features
- Types: Infers string types for your existing regular expressions, including positional and named captures
- Parity: Supports 100% of features allowed by
new RegExp() - Safety: Syntax errors like referencing a group that doesn't exist are now type errors
- Zero Runtime: Improves your type safety without impacting your bundle size
FAQ
Why aren't some patterns like [a-Z] inferred more precisely?
Constructing string literal types for these sorts of expressions is combinatorial and will explode very quickly if we infer character ranges like this as literal characters.
We've tried to strike a balance between performance and precision while guaranteeing that the inferred types are at worst imprecise and never incorrect.
Why doesn't it work with my massive RegExp?
If your expression is especially long or complex, TypeScript won't be able to infer it.
If your types start to slow down or you see the dreaded Type is excessively deep..., you can manually type your expression using regex.as:
Is it robust?
arkregex types are extensively tested and benchmarked using attest.
If anything not covered by the other FAQs is not behaving how you'd expect, please don't hesitate to create an issue.
How can I get syntax highlighting for my expressions?
The ArkType extension can be installed to add syntax highlighting to regex calls.
Useful links
â Check out the project on GitHub
đ Join our Discord to lurk or ask questions
- Follow any of these accounts for updates:
- @arktype.io, @ssalbdivad.dev on BlueSky
- @arktypeio, @ssalbdivad on X/Twitter