Most TypeScript pain comes from fighting the narrowing engine instead of working with it. These are the patterns I use constantly, the bread and butter that keeps a codebase honest.
Each one comes with the mistake it replaces, because the “before” is usually the thing that already exists in the codebase you inherited.
Discriminated unions over optional fields
The single biggest improvement you can make to a data model is replacing “bag of optionals” with a tagged union:
interface Request { status: string; data?: User[]; error?: string;}
type Request = | { status: 'loading' } | { status: 'success'; data: User[] } | { status: 'error'; error: string };Now request.data simply does not exist unless status === 'success'. Whole categories of “why is data undefined here” bugs stop compiling.
The pattern scales. A payment event, a form state, a WebSocket message: anything with a mode has a discriminant. The key rule is that the discriminant is a literal type ('success', 404, true), not string. TypeScript can only narrow on literals.
Assertion functions at the boundaries
Data from the outside world (APIs, forms, file reads) should pass through an assertion exactly once:
export function assertUser(value: unknown): asserts value is User { if ( typeof value !== 'object' || value === null || typeof (value as User).id !== 'string' ) { throw new Error('Invalid user payload'); }}After the call site, TypeScript treats the value as User with no casting. The unsafe cast lives in one audited function instead of being scattered across the codebase as as User.
const res = await fetch('/api/me');const user = (await res.json()) as User; // hoperenderProfile(user.name.toUpperCase()); // runtime crash if the API changedconst res = await fetch('/api/me');const body: unknown = await res.json();assertUser(body); // throws here, with a useful messagerenderProfile(body.name.toUpperCase()); // body is User from this line onFor anything bigger than a couple of fields, write the assertion with a schema library and let it generate the type:
import { z } from 'zod';
const User = z.object({ id: z.string(), name: z.string(), email: z.email() });type User = z.infer<typeof User>;
const user = User.parse(await res.json()); // typed and validatedSame boundary, same single point of trust, but the schema and the type can never drift apart.
satisfies for config objects
satisfies checks a value against a type without widening it:
const routes = { home: '/', blog: '/blog', projects: '/projects',} satisfies Record<string, `/${string}`>;
routes.blog; // type is '/blog', not stringYou get validation and precise literal types. Before satisfies, you had to choose one.
Where this earns its keep is any config-shaped object: theme tokens, route tables, feature flags, i18n dictionaries. Compare the three ways of writing the same thing:
| Approach | Catches typos | Keeps literal types | Autocomplete on keys |
|---|---|---|---|
| No annotation | No | Yes | Yes |
const routes: Routes = … | Yes | No (widened) | Yes |
… satisfies Routes | Yes | Yes | Yes |
Exhaustiveness with never
Close the loop on unions with a default branch that fails to compile when a variant is added:
function label(status: Request['status']): string { switch (status) { case 'loading': return 'Loading…'; case 'success': return 'Done'; case 'error': return 'Failed'; default: return status satisfies never; }}Add a 'cancelled' variant next quarter and this function becomes a compile error instead of a silent bug. The error message even names the missing case.
Type predicates for filtering
Array.prototype.filter does not narrow on its own. This is the mistake I see most in otherwise-strict codebases:
const ids = [user.id, maybeOrg?.id].filter(Boolean); // (string | undefined)[]The filtered array still has undefined in its type. The fix is a predicate that states what survives the filter:
function isDefined<T>(value: T | null | undefined): value is T { return value != null;}
const ids = [user.id, maybeOrg?.id].filter(isDefined); // string[]One tiny helper, exported from a shared module, removes dozens of non-null assertions. It also composes: .filter(isDefined).map(...) reads better than the same code with an ! on every line.
The in operator for structural narrowing
When you do not control the types (third-party SDKs, event payloads from different sources) there is often no discriminant to switch on. The in operator narrows on the presence of a property:
type Success = { data: Report };type Failure = { error: Error; retryAfter?: number };
function handle(result: Success | Failure) { if ('error' in result) { return scheduleRetry(result.retryAfter ?? 30); // Failure } return render(result.data); // Success}It is less robust than a real discriminant (a Success that later grows an optional error field breaks it), so I use it at the edges and convert to a tagged union as soon as the data is mine.
The habit that ties it together
Every pattern here does the same thing: it moves a runtime check to a place where the compiler can see it, so the check happens once and the type system carries the knowledge everywhere else.
| Pattern | Where the check lives | What it eliminates |
|---|---|---|
| Discriminated unions | The type itself | Impossible states |
| Assertion functions | The I/O boundary | Scattered as casts |
satisfies | Config declarations | Widened literal types |
satisfies never | The default branch | Unhandled new variants |
| Type predicates | The filter callback | Non-null assertions |
in narrowing | Third-party edges | Manual property probing |
If you adopt one thing from this list, make it discriminated unions. Everything else gets easier once the data model stops lying.