Types as Specifications
What you'll learn: How to use TypeScript's type system to encode your program's requirements and business rules directly into types, making invalid states unrepresentable.
The Specification Mindset
Think of types as a contract or blueprint before you write implementation code. In type-driven design, you start by asking: "What should be possible? What should be impossible?" Then you encode those answers as types.
Instead of writing code and hoping it's correct, you define the shape of correctness first. The compiler then guides you toward valid implementations and blocks invalid ones.
Types That Enforce Business Rules
Consider a payment processing system. Rather than documenting rules in comments, encode them in types:
type PaymentStatus = 'pending' | 'approved' | 'declined' | 'refunded';
type PendingPayment = {
status: 'pending';
amount: number;
createdAt: Date;
};
type ApprovedPayment = {
status: 'approved';
amount: number;
createdAt: Date;
approvedAt: Date;
transactionId: string;
};
type Payment = PendingPayment | ApprovedPayment | /* other variants */;
The type system now enforces that approved payments have transactionId and approvedAt fields. You cannot create an approved payment without them—the compiler won't allow it.
Specifications as Documentation
Types serve as executable specifications. When a function signature says it accepts ApprovedPayment, that's not just a hint—it's a guarantee. The type tells you exactly what data must exist and what operations are safe.
This eliminates guesswork. No need to dig through implementation code or documentation that might be outdated.
Key Takeaway: Types as specifications means encoding your system's requirements and constraints directly into the type system, making the compiler your first line of defense against logic errors and invalid states.