TypeScript · Lesson 38 of 120
Practice: Payment Results
Unions together.
Let's practise unions. A payment can succeed, fail, or need more checks. We'll model each result as a shape with a status field, and handle every case.

- Success
- Failure
- More checks
Handling every result
Result is a discriminated union, on status. Message handles each status, using the fields only that shape has. The default branch makes it exhaustive. Run it.
app.tstypescript
type PaymentResult =
| { status: "ok"; receipt: string }
| { status: "declined"; reason: string }
| { status: "verify"; url: string };
function message(r: PaymentResult): string {
switch (r.status) {
case "ok": return `Paid! Receipt ${r.receipt}`;
case "declined": return `Declined: ${r.reason}`;
case "verify": return `Please verify at ${r.url}`;
default: { const missed: never = r; return missed; }
}
}
console.log(message({ status: "ok", receipt: "R-881" }));
console.log(message({ status: "declined", reason: "insufficient funds" }));Output
Paid! Receipt R-881 Declined: insufficient funds
Summary
Discriminated unions and exhaustive switches model results cleanly. Next, the unions quiz.
Key takeaways- status field
- switch
- never
Next up: Unions Quiz — test yourself