Hasty Briefsbeta

Bilingual

Parse, Don't Validate – In a Language That Doesn't Want You To

2 hours ago
  • #Parsing
  • #Validation
  • #TypeScript
  • Discusses the principle of 'Parse, don't validate' from Alexis King's 2019 post, emphasizing that parsers preserve type information while validators discard it after checking.
  • Illustrates common TypeScript validation pitfalls with an example where User.email remains just a string after validation, requiring repeated checks.
  • Proposes using branded types (e.g., Email and Age with unique symbols) in TypeScript to create nominal-like types, ensuring parsed data is trusted throughout the codebase.
  • Provides code examples for parsers that return discriminated unions (Parsed<T>) for error handling, making failures explicit in the type system.
  • Compares TypeScript's approach to languages like Haskell or Elm, noting structural typing's challenges and the need for manual discipline to enforce parsing boundaries.
  • Mentions libraries like Zod or io-ts as ergonomic tools that generate parsers and types from schemas but stresses that mindset and discipline are still crucial.
  • Highlights TypeScript's limitations, such as requiring type assertions (as Email) in parsers and lacking exhaustive pattern matching, though suggests using never for exhaustiveness checks.
  • Advocates for separating unvalidated data (unknown) from validated domain types (e.g., ValidUser) to make illegal states unrepresentable and improve code safety.