Advanced Types - Unions, Intersections, and Type Guards
The $50,000 Payment Bug That Wasn't
// payment-processor.js - Old JavaScript
function processTransaction(transaction) {
if (transaction.type === 'charge') {
return chargeCard(transaction.amount, transaction.cardToken);
} else if (transaction.type === 'refund') {
return refundCard(transaction.amount, transaction.cardToken);
}
// What if transaction.type was 'authorization'?
// Or 'void'? Or a typo like 'reund'?
// Silently returns undefined!
}type TransactionType = 'charge' | 'refund' | 'authorization' | 'void';
interface Transaction {
id: string;
type: TransactionType;
amount: number;
cardToken: string;
}
function processTransaction(transaction: Transaction): Promise<TransactionResult> {
switch (transaction.type) {
case 'charge':
return chargeCard(transaction.amount, transaction.cardToken);
case 'refund':
return refundCard(transaction.amount, transaction.cardToken);
case 'authorization':
return authorizeCard(transaction.amount, transaction.cardToken);
case 'void':
return voidTransaction(transaction.id);
default:
// TypeScript ensures this is never reached
const exhaustiveCheck: never = transaction.type;
throw new Error(`Unhandled transaction type: ${exhaustiveCheck}`);
}
}Union Types
Basic Union Types
Union with Multiple Types
Union with null and undefined
Type Narrowing
typeof Type Guards
Truthiness Narrowing
Equality Narrowing
in Operator Narrowing
instanceof Narrowing
Discriminated Unions
Basic Discriminated Union
Real-World Example: API Response
Exhaustiveness Checking
Intersection Types
Basic Intersection
Intersection with Multiple Types
Extending Interfaces vs Intersections
Literal Types
String Literal Types
Number Literal Types
Boolean Literal Types
Combining Literals
Type Predicates
Basic Type Predicate
Object Type Predicates
Array Type Predicates
Assertion Functions
Basic Assertion Function
Type Assertion Functions
Real-World Example
Real-World Patterns
1. Form State Management
2. Event Handling
3. Result Type Pattern
Common Mistakes I Made
1. Not Narrowing Unions
2. Forgetting Exhaustiveness Checks
3. Using Type Assertions Instead of Narrowing
Your Challenge
Key Takeaways
What I Learned
Last updated