RSS Amplifier

Steven Kalt · Oct 10, 2024

Implementing Regular Expressions in TypeScript Types (Badly)

0
Sign in to vote or save

This page cannot be shown here. You can still read it on the original site — the toolbar below keeps your place in the directory.

Summary This is a cautionary tale about how I ended up writing a (bad) regular expression parser and evaluator in pure TypeScript types. type HexStr < S extends string > = Recognize < "[0-9a-fA-F]+" , S > ; type IsMatch < S extends string > = HexStr < S > extends S ? true : false ; const isHex : IsMatch < "deadbeef" > = true const notHex : IsMatch < "nope" > = false The novelty here is parsing and…

Summary

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

type HexStr<S extends string> = Recognize<"[0-9a-fA-F]+", S>;
type IsMatch<S extends string> = HexStr<S> extends S
 ? true
 : false;
const isHex: IsMatch<"deadbeef"> = true
const notHex: IsMatch<"nope"> = false

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.

Backstory

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:

Read on /projects/brzozowski_ts/

Comments

Nothing yet. Say the first thing.

    Sign in to join the conversation.