Type Narrowing Without the Boilerplate
Take a typical case, made up for illustration. A payments team added a new status, requires_action, for 3-D Secure. The order page assumed every unsuccessful payment had a failure object and read payment.failure.message. For customers in the 3-D Secure flow, the page threw on load. Twelve places in the app branched on payment status, and none of them had been told about the new one.
Narrowing is how TypeScript turns “this could be several things” into “this is exactly this thing here”. Done well, a new case becomes a compile error in every place that must handle it. Below is built-in narrowing, discriminated unions, exhaustive checks, custom predicates (and how they can lie), unknown in catch blocks, and the inferred predicates newer TypeScript gives you for free.
- You write
as SomeTypeto silence the compiler instead of narrowing properly - You have runtime checks that TypeScript doesn't respect because you didn't use a type predicate
- Your discriminated unions fall through to
neverin switch statements and you're not sure why - You're repeating the same
if (typeof x === 'string')checks everywhere instead of extracting a guard
Discriminated unions + exhaustive switch statements eliminate entire categories of runtime errors that type assertions only hide.
Built-in Narrowing
typeof
function format(value: string | number | boolean): string {
if (typeof value === 'string') {
return value.toUpperCase(); // TypeScript knows: value is string here
}
if (typeof value === 'number') {
return value.toFixed(2); // value is number here
}
return String(value); // value is boolean here
}
// typeof only narrows to JS primitives:
// 'string' | 'number' | 'bigint' | 'boolean' | 'symbol' | 'undefined' | 'function' | 'object'
// Note: typeof null === 'object' — always check null separatelyinstanceof
class NetworkError extends Error {
constructor(public status: number, message: string) {
super(message);
this.name = 'NetworkError';
}
}
class ValidationError extends Error {
constructor(public field: string, message: string) {
super(message);
this.name = 'ValidationError';
}
}
function handleError(error: unknown): string {
if (error instanceof NetworkError) {
return `Network ${error.status}: ${error.message}`;
}
if (error instanceof ValidationError) {
return `Validation on '${error.field}': ${error.message}`;
}
if (error instanceof Error) {
return error.message;
}
return 'Unknown error';
}in operator
interface Cat { meow(): void; }
interface Dog { bark(): void; }
function makeSound(animal: Cat | Dog): void {
if ('meow' in animal) {
animal.meow(); // animal is Cat
} else {
animal.bark(); // animal is Dog
}
}
// Useful for optional properties too
interface Config {
timeout?: number;
endpoint: string;
}
function logConfig(config: Config) {
if ('timeout' in config && config.timeout !== undefined) {
console.log('Timeout:', config.timeout); // number, not number | undefined
}
}Discriminated Unions: The Most Powerful Pattern
A discriminated union is a union type where every member has a common literal property (the discriminant). TypeScript uses this to narrow in switch statements with total exhaustiveness checking.
flowchart TD
result["Result: Success | Failure | Pending"]
result -->|"status === 'success'"| s["data: T is available"]
result -->|"status === 'failure'"| f["error: string is available"]
result -->|"status === 'pending'"| p["Neither — still loading"]
style s fill:#16a34a,color:#fff,stroke:#15803d
style f fill:#dc2626,color:#fff,stroke:#b91c1c
style p fill:#0078D4,color:#fff,stroke:#005a9e
type Result<T> =
| { status: 'success'; data: T }
| { status: 'failure'; error: string; code: number }
| { status: 'pending' };
function processResult<T>(result: Result<T>): string {
switch (result.status) {
case 'success':
return JSON.stringify(result.data); // data is T — no assertion needed
case 'failure':
return `Error ${result.code}: ${result.error}`; // error and code available
case 'pending':
return 'Loading...';
default:
// Exhaustiveness check — TypeScript catches missing cases
const _never: never = result;
throw new Error(`Unhandled status: ${String(_never)}`);
}
}Custom Type Predicates
When built-in narrowing isn't enough, write a function that returns value is Type — a type predicate. TypeScript trusts your runtime check and narrows accordingly.
// Type predicate: tells TS "if this returns true, value is User"
function isUser(value: unknown): value is User {
return (
typeof value === 'object' &&
value !== null &&
'id' in value &&
typeof (value as any).id === 'string' &&
'name' in value &&
typeof (value as any).name === 'string'
);
}
// Usage
const data: unknown = await fetchData();
if (isUser(data)) {
console.log(data.name); // ✅ TypeScript knows data is User
} else {
console.log('Not a user');
}
// Filter arrays to narrow types
const maybeUsers: unknown[] = getItems();
const users: User[] = maybeUsers.filter(isUser); // filter narrows the array typeAssertion Functions (TypeScript 3.7+)
Assertion functions throw on failure — they're useful in constructors and functions where you want to narrow the type for the rest of the current scope.
function assertIsString(value: unknown): asserts value is string {
if (typeof value !== 'string') {
throw new TypeError(`Expected string, got ${typeof value}`);
}
}
const maybeString: unknown = getConfig('name');
assertIsString(maybeString); // throws if not string
// From this point on, maybeString is narrowed to string
console.log(maybeString.toUpperCase()); // ✅ no assertion neededThe unknown Pattern for Catch Blocks
TypeScript 4.4+ types catch clause variables as unknown by default under strict mode (via the useUnknownInCatchVariables flag) — 4.0 only added the ability to annotate them that way by hand. Proper type guards here prevent runtime errors in error handling code.
try {
await dangerousOperation();
} catch (error) {
// error is unknown — you must narrow before using
if (error instanceof Error) {
console.error(error.message); // ✅
} else if (typeof error === 'string') {
console.error(error); // ✅
} else {
console.error('Unknown error:', JSON.stringify(error));
}
}
// Reusable helper
function getErrorMessage(error: unknown): string {
if (error instanceof Error) return error.message;
if (typeof error === 'string') return error;
return 'An unexpected error occurred';
}Inferred Predicates and satisfies
Two newer features remove most of the remaining hand-written narrowing code. Since TypeScript 5.5 the compiler infers a type predicate for simple functions, so filtering out missing values narrows the element type with no annotation.
const ids: (string | undefined)[] = ['a', undefined, 'b'];
// Before 5.5 this was still (string | undefined)[] unless you wrote (x): x is string
const present = ids.filter((x) => x !== undefined); // string[]Inference only applies when the function returns a single boolean expression and does not mutate its argument. For anything more involved you still write the predicate yourself, and it is still a promise the compiler does not check, so keep those functions small and tested.
satisfies checks that a value matches a type without widening the value to that type. You get the validation and keep the precise literal types for later narrowing.
type Route = { path: string; auth: boolean };
const routes = {
home: { path: '/', auth: false },
orders: { path: '/orders', auth: true },
} satisfies Record<string, Route>;
type RouteName = keyof typeof routes; // 'home' | 'orders' — the keys were not widened to string
// A route without 'auth', or with a misspelled key, is a compile error at the declaration.When Narrowing Quietly Stops
Narrowing is flow analysis, and the compiler is deliberately conservative about anything that could change between the check and the use. Three situations lose a narrowing that looked solid:
// 1. A mutable variable captured by a callback
let payment: Payment | undefined = await load();
if (payment) {
setTimeout(() => payment.amount, 0); // error if payment is reassigned anywhere later
}
// 2. A property checked, then an await in between
if (order.payment.status === 'succeeded') {
await audit(order); // could have mutated order
order.payment.receiptUrl; // still narrowed by TS, but is it still true?
}
// 3. A discriminant read through a function call
if (getStatus(payment) === 'failed') {
payment.failure.message; // error: the call result does not narrow payment
}The fixes are dull and reliable. Copy the narrowed value into a const before the callback or the await, so there is nothing left to change. Check the discriminant property itself (payment.status) rather than a helper’s return value, or turn the helper into a type predicate. Case 2 deserves a comment of its own: TypeScript keeps the narrowing across theawait, because tracking every possible mutation would make narrowing useless, so the compiler trusts you there. If other code can change the object, re-read it after the await.
Validate at the Edge, Narrow Inside
A hand-written guard such as isPayment(x: unknown): x is Payment is a promise the compiler cannot check. It is fine for a two-field object. For anything that crosses a trust boundary (an API response, a queue message, a webhook body), use a schema library at that boundary and let it produce the typed value. Inside your code, data is already the right shape, and narrowing becomes purely about which variant you have.
That division is what prevents the requires_action incident. The schema accepts only the statuses you know, so an unknown status fails loudly at the boundary instead of reaching the page. And inside, every switch on status ends with an exhaustive check, so adding the new status breaks the build in all twelve places at once:
function paymentBanner(p: Payment): string {
switch (p.status) {
case 'succeeded': return 'Paid';
case 'failed': return p.failure.message;
case 'requires_action': return 'Confirm the payment with your bank';
default: {
const unhandled: never = p; // compile error when a status is added
throw new Error(`Unhandled status: ${JSON.stringify(unhandled)}`);
}
}
}Pitfalls
Type assertions vs type guards
// ❌ Type assertion — silences the error but doesn't check at runtime
const user = data as User; // no runtime check: if data isn't a User, later code may crash or quietly misbehave
// ✅ Type guard — validates at runtime AND narrows the type
if (isUser(data)) {
const user = data; // User — safe
}Forgetting the exhaustiveness check
Always include the default: const _never: never = ... pattern in switch statements over discriminated unions. Without it, adding a new union member compiles fine but silently hits the missing case at runtime.
Guards That Stay Honest
A type predicate is a promise that the compiler takes at face value. If you write x is User and only check one field, TypeScript believes you, and the bug shows up at runtime somewhere far away. For data from outside your program, use a schema library rather than a hand-written guard, so that the check and the type can't drift apart. Since TypeScript 5.5, the compiler can infer simple predicates by itself from a function body, which removes many hand-written ones. Check whether you still need yours, because an inferred guard can't lie.
Narrowing Pitfalls
Narrowing is optimistic. A check on obj.value usually survives a function call, even though that function could have changed it, so the compiler can be wrong here. If a call might mutate the value, copy it into a const first or check again. Narrowing does stop inside callbacks for mutable variables.
Prefer discriminated unions to optional fields. A { status: 'ok'; data: T } | { status: 'error'; error: string } makes invalid states impossible. Add an exhaustive check with satisfies never in the default branch, and adding a new status becomes a compile error at every switch that doesn't handle it.