Get the latest tech news
Implementing Regular Expressions in TypeScript Types (Badly)
his 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.
This is a cautionary tale about how I ended up writing a (bad) regular expression parser and evaluator in pure TypeScript types. a large set of probably long, potentially infinite-length strings with a tricky-yet-regular pattern (e.g. CSVs): parse the input at runtime. Write test-cases as you develop You can put the test cases next to your type-under-construction using block scopes to avoid polluting your module’s namespace:
Or read this on Hacker News