Unions and narrowing
Real data comes in more than one shape: an ID might be a number or a string, an API call might succeed or fail. Union types describe "this OR that", and narrowing lets TypeScript know which one you have.
Union types: A | B
With a union, you can only use what all members share, until you narrow it down.
Narrowing with typeof
TypeScript follows your if, return, switch and && logic and narrows the type inside each branch. This is called control-flow analysis.
Handling null and undefined
With strict mode on (always turn it on!), null and undefined are not allowed unless you say so. This eliminates the most common JavaScript crash, "Cannot read properties of undefined":
Other narrowing techniques
Discriminated unions: the most useful pattern in TypeScript
Give every member of a union a shared literal property (often called type, kind or status). Checking it narrows to the exact member:
This makes impossible states impossible: you can't have data while status is 'error'. Redux actions, API results and UI state machines all use this pattern.
Exhaustiveness checking with never
What if someone adds a new status later and forgets to handle it? Make the compiler catch it:
Add a case 'triangle' and the error disappears.
Custom type guards
Write your own narrowing function with value is Type:
Practice
Model the result of a payment as a discriminated union, with 'paid' (amount, receiptId), 'declined' (reason) and 'pending' (retryInSeconds). Write paymentMessage(result) using a switch with an exhaustive never check.
1.Given value: string | number, what does if (typeof value === 'string') { ... } do?
2.What makes a union "discriminated"?