Payment State Modeling: Preventing Invalid States
You'll learn how to use discriminated unions to make impossible payment states like isPending and isCompleted both being true literally impossible to represent in TypeScript.
The Problem: Boolean Soup
Imagine modeling payment state with booleans:
type Payment = {
isPending: boolean;
isCompleted: boolean;
isFailed: boolean;
amount: number;
errorMessage?: string;
};
This allows nonsensical states:
const brokenPayment: Payment = {
isPending: true,
isCompleted: true, // ??? Both pending AND complete?
isFailed: false,
amount: 100
};
The type system can't prevent isPending and isCompleted from both being true. You need runtime checks everywhere, and bugs slip through.
The Solution: Discriminated Union by State
Model each valid state as its own type, then unite them:
type Payment =
| { status: 'pending'; amount: number }
| { status: 'completed'; amount: number; confirmedAt: string }
| { status: 'failed'; amount: number; errorMessage: string };
Now the impossible is structurally impossible:
// TypeScript error: can't have both status values
const broken: Payment = {
status: 'pending',
status: 'completed' // Error!
};
Each state carries only the data that makes sense for it—confirmedAt only exists when completed, errorMessage only when failed.
Why This Matters
With discriminated unions, exhaustive checks protect you:
function processPayment(payment: Payment) {
switch (payment.status) {
case 'pending':
return `Processing ${payment.amount}...`;
case 'completed':
return `Completed at ${payment.confirmedAt}`;
case 'failed':
return `Failed: ${payment.errorMessage}`;
}
}
Add a new state like 'refunded'? TypeScript forces you to handle it everywhere.
Key Takeaway: Using discriminated unions instead of boolean flags eliminates entire categories of invalid states at compile time, turning runtime bugs into type errors you catch before shipping.