Skip to content

Engineering

TypeScript narrowing patterns I reach for every week

Discriminated unions, assertion functions, and the satisfies operator: a working tour of the narrowing techniques that do the most work in a real codebase.

Alex Carter4 min read

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:

src/types.ts
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:

src/lib/assert.ts
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; // hope
renderProfile(user.name.toUpperCase()); // runtime crash if the API changed
const res = await fetch('/api/me');
const body: unknown = await res.json();
assertUser(body); // throws here, with a useful message
renderProfile(body.name.toUpperCase()); // body is User from this line on

For 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 validated

Same 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 string

You 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:

ApproachCatches typosKeeps literal typesAutocomplete on keys
No annotationNoYesYes
const routes: Routes = …YesNo (widened)Yes
… satisfies RoutesYesYesYes

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.

PatternWhere the check livesWhat it eliminates
Discriminated unionsThe type itselfImpossible states
Assertion functionsThe I/O boundaryScattered as casts
satisfiesConfig declarationsWidened literal types
satisfies neverThe default branchUnhandled new variants
Type predicatesThe filter callbackNon-null assertions
in narrowingThird-party edgesManual property probing

If you adopt one thing from this list, make it discriminated unions. Everything else gets easier once the data model stops lying.

Share
All articles

Alex Carter

Full-stack Developer

Get new posts by email

One email when I publish something new. No digests, no spam, unsubscribe in one click.

No spam, ever. Unsubscribe with one click.

Related articles

↑↓ navigate↵ openesc close