Implementing Regular Expressions in TypeScript Types (Badly)

submited by
Style Pass
2024-10-17 02:00:04

This is a cautionary tale about how I ended up writing a (bad) regular expression parser and evaluator in pure TypeScript types.

The novelty here is parsing and evaluating regular expressions at compile-time. The inspiration for this technique came from a comment from 2020 on the RegEx-validated string type discussion.

To prepare for Halloween, I was writing a function castSpell that accepts a valid hex string. I was writing in TypeScript, so the usual way to do this is using branded types, also known as nominal types:

TypeScript’s type system is Turing-complete, so parsing and evaluating regular expressions is definitely possible. I’ve already see things like solving N-Queens, parsing and evaluating SQL, or implementing deterministic finite automata in the wild.

Ignoring the question of “should I do this”, only the question “how to check if a RegEx matches a string at compile-time” remains.

Leave a Comment