How to Type Check Regex with TypeScript

TypeScript 5.5 Beta is available and brings a fantastic feature to help developers catch common errors in regular expressions: regex syntax checking.

This means that TypeScript can now detect mistakes in regular expressions at compile time, saving you from runtime errors and debugging headaches.

Here's a quick guide on how to use this new feature:

How to

No keywords are needed; it just works!

As an example, if you have a mismatched parenthesis, TypeScript will catch it.

let myRegex = /@robot(\s+(please|immediately)))? do some task/;
//                                            ~
// error!
// Unexpected ')'. Did you mean to escape it with a backslash?

Limitations

Currently, TypeScript's regex checking only applies to regex literals. If you create a regex using the RegExp constructor with a string, TypeScript won't check it.

let myRegex = new RegExp("@typedef \\{import\\((.+)\\)\\.([a-zA-Z_]+)\\} \\3");
// TypeScript will not check this regex for errors.

It does a few really smart things, and if you want to check out more advanced usage, I'd check out the release notes here.

TypeScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.