Course contentsShow
← TypeScript
Lesson 1365 of 1,79631. Type-Driven DesignFree lesson

Combining Validation with Types

Integrate runtime validation logic inside smart constructors to guarantee type invariants.

Combining Validation with Types

What you'll learn: How to integrate runtime validation directly into smart constructor functions to guarantee your types always hold valid data.


The Core Idea

You've learned how to brand types and create smart constructors. Now it's time to combine them with actual validation logic. Instead of just trusting that you pass valid data, you enforce validity at construction time. The smart constructor becomes the only way to create your branded type, and it refuses to return that type unless the data passes validation.

This creates a powerful guarantee: if a value has your branded type, it must be valid. No exceptions.


Plain English Explanation

Think of a smart constructor like a security checkpoint at an airport. You can't just walk through to the secure area—you must pass through validation (ID check, scanner, etc.). Once you're through, everyone knows you've been validated. They don't need to check you again.

Similarly, once a value has passed through your smart constructor and received the branded type, the rest of your codebase can trust it completely. No defensive checks needed everywhere.


The Pattern in Practice

Your smart constructor function:

  1. Accepts a primitive value (like string or number)
  2. Validates it against your business rules
  3. Returns either the branded type or signals failure (via null, throwing, or a Result type)

The key: validation happens once, at the boundary. After that, the type system carries the guarantee forward.


Why This Matters

This approach makes invalid states unrepresentable at the type level. Instead of scattered validation checks throughout your code, you validate once and let types prove correctness everywhere else. It's type-driven design at its finest.


Key Takeaway: Smart constructors that combine runtime validation with branded types ensure your domain invariants are enforced at construction time, making invalid data impossible to represent in your typed system.