HeadlinesBriefing favicon HeadlinesBriefing.com

Parse Don't Validate: TypeScript Branded Types Fix

Hacker News •
×

The 'Parse, don't validate' principle, popularized by Alexis King, challenges developers to transform raw data into precise types rather than merely checking validity. In TypeScript, this approach ensures that once data is parsed—like an email address—it remains trustworthy throughout the codebase. However, TypeScript's structural typing system complicates this, as validation functions return boolean values without updating the type system.

To bridge this gap, developers use branded types—phantom type markers that create distinct types like `Email` or `Age`. By intersecting base types with unique symbols, these branded types prevent invalid data from being used where valid data is expected. This technique forces developers to handle parsing failures explicitly, making illegal states unrepresentable at compile time.

The parsing functions return `Parsed<T>` results, encoding success or failure in the type system rather than throwing exceptions. This approach eliminates defensive checks scattered throughout codebases, as the type system itself guarantees data integrity after parsing. Once validated, the data carries its proof of correctness forward.

TypeScript's structural typing doesn't enforce this discipline by default, unlike languages like Haskell or Elm. But branded types offer a pragmatic compromise, allowing teams to adopt parse-over-validate patterns without leaving the language. The result is fewer runtime errors and clearer code intent.