TypeScript Patterns That Make Wrong Code Fail to Compile
Five TypeScript patterns that make wrong code fail to compile, chosen for codebases where more of the code is AI-generated. Includes a PR review checklist.
A reviewer can hold a handful of rules in their head while reading a diff. The compiler holds all of them, on every file, and it doesn't get tired on the sixth AI-generated pull request of the afternoon. That's the whole case for the TypeScript patterns in this post: each one moves a rule out of somebody's memory and into a type, so the wrong version of the code stops compiling.
This matters more now than it did a few years ago. A growing share of the code landing in your repo was written by an assistant, or by an engineer who joined last month and doesn't know that order IDs and user IDs are both strings for historical reasons. Generated code is fluent. It looks like the code around it. The failures I worry about are the plausible ones, and plausible is exactly what a tired reviewer waves through. (The reviewing side has its own post: how to review AI-generated code.)
Here's my contrarian take, stated as an opinion: the TypeScript that protects a codebase is mostly boring. Fewer generics, more unions. Fewer clever conditional types, more small functions that parse input and return a precise type. The type-level puzzles people share on social media make reviews harder, not safer.
Every codebase has invariants that live only in people's heads. "Amounts are in cents." "Every payment kind needs a settlement path." "Never trust the webhook body." A senior engineer enforces these in review by remembering them. That works until the senior engineer is on holiday, or the diff is enormous, or the author is a model that never heard the rule.
A type encodes the decision once. After that, the check runs on every build, for every author, and the error message lands in the editor before anyone opens a pull request. If your team uses agents that run tsc in a loop, the compiler error is also feedback the agent can act on, which a reviewer's comment two days later is not.
The five patterns below are the ones I'd put in every TypeScript codebase. Every snippet in this post was compiled with TypeScript 7.0.2 and the flags recommended later on, and the lines marked as errors do fail.
# Pattern 1: discriminated unions with an exhaustive switch
When every member of a union shares a property with a literal type, TypeScript treats it as a discriminated union and narrows on that property. Narrow away every possibility and what's left is never, a type nothing else can be assigned to. That gives you an exhaustiveness check for free.[1]
typescript
type Payment = | { kind: "card"; last4: string } | { kind: "bank"; iban: string } | { kind: "wallet"; provider: "apple" | "google" };function assertNever(value: never): never { throw new Error(`Unhandled case: ${JSON.stringify(value)}`);}export function settle(p: Payment): void { switch (p.kind) { case "card": chargeCard(p.last4); break; case "bank": queueTransfer(p.iban); break; case "wallet": requestWalletAuth(p.provider); break; default: assertNever(p); // compile error the day someone adds a fourth kind }}declare function chargeCard(last4: string): void;declare function queueTransfer(iban: string): void;declare function requestWalletAuth(provider: "apple" | "google"): void;
Add | { kind: "crypto"; network: string } to Payment and the build fails at assertNever(p) with "Argument of type '{ kind: "crypto"; network: string; }' is not assignable to parameter of type 'never'." Every switch over Payment that carries this check lights up, which is exactly the list of places the new member needs handling.
Delete the default branch and the same change compiles cleanly, with no case that handles crypto. That's the dangerous version. A function that returns void, or one whose return type is inferred, has no missing-return error to save you. With an explicit string return type TypeScript would complain about the missing return anyway, but most event handlers and side-effecting code don't look like that.
Figure 1. With an assertNever default, adding a union member breaks the build at every switch that needs updating; without it, the change compiles silently.
If you'd rather enforce this with a linter, typescript-eslint has a switch-exhaustiveness-check rule. It needs type information, so it runs slower than syntax-only rules, but it catches the switches people forgot to give a default.[2]
Structural typing means UserId and OrderId are interchangeable if both are string. So are Cents and Dollars if both are number. A brand adds a phantom property that exists only at compile time, which makes those types distinct without changing anything at runtime.
typescript
declare const brand: unique symbol;type Brand<T, B extends string> = T & { readonly [brand]: B };type UserId = Brand<string, "UserId">;type OrderId = Brand<string, "OrderId">;type Cents = Brand<number, "Cents">;export function toOrderId(raw: string): OrderId { if (!/^ord_[a-z0-9]{12}$/.test(raw)) throw new Error(`Not an order id: ${raw}`); return raw as OrderId; // the one sanctioned cast, inside the constructor}export function toCents(amount: number): Cents { if (!Number.isSafeInteger(amount)) throw new Error(`Not whole cents: ${amount}`); return amount as Cents;}declare function refund(order: OrderId, amount: Cents): Promise<void>;declare const userId: UserId;refund(toOrderId("ord_8f3k2m9x1q7z"), toCents(500)); // compilesrefund(userId, toCents(500)); // error: UserId is not OrderIdrefund(toOrderId("ord_8f3k2m9x1q7z"), 5); // error: number is not Cents
The last two calls fail to compile. Swapped arguments and unit mix-ups are precisely the bugs that slip past review, because the code reads fine.
Be honest about the limit: a brand is a compile-time promise, and an as cast anywhere can forge one. The review rule that makes brands work is simple. Casts to a branded type are allowed only inside its constructor function, which validates first.
# Pattern 3: satisfies for checked config without widening
TypeScript 4.9 added the satisfies operator, which validates that an expression matches a type without changing the type of the expression. That's the right tool for config objects, route tables and feature-flag maps.[3]
typescript
type Plan = "free" | "team" | "enterprise";type Limits = { seats: number; aiReviewsPerMonth: number | "unlimited" };export const planLimits = { free: { seats: 3, aiReviewsPerMonth: 50 }, team: { seats: 50, aiReviewsPerMonth: 2000 }, enterprise: { seats: 10000, aiReviewsPerMonth: "unlimited" },} satisfies Record<Plan, Limits>;// Still a number here, not number | "unlimited"export const freeQuota = planLimits.free.aiReviewsPerMonth.toFixed(0);
Misspell enterprise as enterprize and the compiler says the property doesn't exist in Record<Plan, Limits> and suggests the right name. Write the same object with a type annotation instead (const planLimits: Record<Plan, Limits> = ...) and the typo is still caught, but planLimits.free.aiReviewsPerMonth widens to number | "unlimited" and the toFixed call stops compiling. With satisfies you get the check and keep the precise type.
My default for a fixed set of values is a plain object with as const, plus a type derived from its values.
typescript
export const Role = { Admin: "admin", Reviewer: "reviewer", Viewer: "viewer",} as const;export type Role = (typeof Role)[keyof typeof Role]; // "admin" | "reviewer" | "viewer"export function canMerge(role: Role): boolean { return role === Role.Admin || role === Role.Reviewer;}canMerge(Role.Viewer);canMerge("admin"); // plain strings from JSON or a database still type-check
Three reasons I prefer it. First, a string enum rejects the literal "admin", so every value coming off the wire needs a cast to become an enum member, and casts are what we're trying to remove. Second, the TypeScript handbook itself says you may not need an enum when an as const object would do, and that this keeps your code aligned with JavaScript. Third, Node can now run TypeScript files by stripping types, and the erasableSyntaxOnly flag rejects enum declarations along with other syntax that has runtime behavior.[4]
When are enums fine? When the codebase already uses them consistently. Churning a working enum into a const object buys you little. Pick one style for new code and write it down.
# Pattern 5: treat outside data as unknown and parse at the boundary
JSON.parse returns any. So does the .json() body method on a fetch Request or Response. The moment an any enters your program, every property access on it type-checks, and the checker has nothing to say about the bug that follows. When something compiled and still crashed in production, a boundary like this is the first place I'd look.
The fix is a rule, not a library, and the schema check happens once: anything from outside the process (HTTP bodies, webhooks, queue messages, environment variables, LLM output, files) is unknown until a parser has checked it. Zod is the common choice. Its current major version is Zod 4, where .parse() throws a ZodError on bad input, .safeParse() returns a result with success plus either data or error, and z.infer derives the static type from the schema so the two can't drift.[5]
typescript
import * as z from "zod";const ReviewEvent = z.object({ prId: z.string().regex(/^pr_\d+$/), verdict: z.enum(["approve", "request_changes", "comment"]), score: z.number().int().min(0).max(100), reviewer: z.string().optional(),});type ReviewEvent = z.infer<typeof ReviewEvent>;export async function handleReviewWebhook(req: Request): Promise<Response> { const body: unknown = await req.json(); // untrusted until parsed const parsed = ReviewEvent.safeParse(body); if (!parsed.success) { return Response.json({ issues: parsed.error.issues }, { status: 400 }); } const event: ReviewEvent = parsed.data; // typed from here inward await recordVerdict(event.prId, event.verdict, event.score); return new Response(null, { status: 204 });}declare function recordVerdict( prId: string, verdict: ReviewEvent["verdict"], score: number,): Promise<void>;
Annotating body as unknown is the important line. Try body.prId without parsing and you get "'body' is of type 'unknown'", which is the compiler refusing to guess. Inside the boundary, functions take typed domain values (ReviewEvent, branded IDs, unions) and never see raw input again. Bad input gets a 400 and never reaches the domain.
Figure 2. Outside data stays unknown until one parse step at the boundary turns it into typed domain values or rejects it.
TypeScript 7.0, released in July 2026 as the native port of the compiler, keeps the default introduced in 6.0: strict is true unless you turn it off. Write it explicitly anyway, so nobody has to know which version changed what. Then add the flags that aren't part of the strict family.[6]
noUncheckedIndexedAccess adds undefined to lookups through index signatures, so reading scores["bob"] from a Record<string, number> gives number | undefined, and calling .toFixed(1) on it fails until you handle the missing key. Array indexing gets the same treatment, including xs[i] inside a classic for loop. exactOptionalPropertyTypes makes theme?: "dark" | "light" mean "absent or one of those two", so { theme: undefined } no longer passes. noImplicitOverride requires the override keyword, which keeps subclasses in sync with their base. noFallthroughCasesInSwitch flags a non-empty case that falls into the next one.[7]
erasableSyntaxOnly is the opinionated one. It also rejects parameter properties and namespaces with runtime code, so treat it as a choice for new code or for projects that run under Node's type stripping.
On an existing codebase, noUncheckedIndexedAccess and exactOptionalPropertyTypes will produce a wave of errors. That wave is a list of places where the code assumed something it never checked. I'd turn them on per package and burn the errors down, rather than leave them off forever because the first count looked scary.
interface User { id: string; email: string; active: boolean }declare const raw: string;declare const users: User[];declare function loadSettings(): unknown;const user = JSON.parse(raw) as User; // trusts the payload, checks nothingconst firstActive = users.find((u) => u.active)!; // promises a match existsconst settings: any = loadSettings(); // switches the checker off downstreamsettings.retries.max.toFixed(); // compiles, crashes at runtimeexport { user, firstActive };
An as cast on external data is a claim with no evidence behind it. A non-null assertion (!) is the same claim about one value. any is worse than both because it spreads: every value derived from it is unchecked too. All three make the red squiggle go away, which is why they're tempting to anyone, human or model, who just wants the build to pass.
The fourth anti-pattern is cleverness. A conditional type that recurses through template literals to infer route params can be impressive and correct. It's also something only its author can review, and its error messages read like ransom notes. If a union, an overload or a small parse function does the job, I'd take that every time.
# A TypeScript review checklist for any pull request
Types are rules that run on every build. Move invariants out of reviewers' heads and into the compiler, especially when more of the code is generated.
Discriminated unions with an assertNever default turn "we added a case" into a list of compile errors at every place that needs updating.
Branded types and satisfies catch swapped arguments, unit mix-ups and config typos that read fine in a diff.
Outside data is unknown until a schema parses it. as on a JSON payload is a guess, not a type.
Turn on strict, noUncheckedIndexedAccess and exactOptionalPropertyTypes, and treat new any, as and ! as review blockers.
The best type error is the one that shows up before anyone reads the diff. Make the compiler the reviewer that never forgets, and spend human review on the questions types can't answer.
Frequently asked questions
Is satisfies better than a type annotation in TypeScript?
For config objects and lookup tables, usually yes. Both catch typos and missing keys, but an annotation widens each value to the declared type, while satisfies checks the object and keeps the precise inferred type. Use an annotation when you actually want the wider type, for example a variable you plan to reassign.
Do I need Zod to validate API data in TypeScript?
No. The rule is that outside data starts as unknown and passes through a parser before the rest of the code sees it. Zod is a common choice because z.infer derives the type from the schema, so the two cannot drift. A hand-written type guard or another schema library works too, as long as every boundary goes through one.
Are TypeScript enums bad?
Not bad, just rarely needed in new code. A string enum rejects plain string literals, so values from JSON need a cast to become members, and the erasableSyntaxOnly flag rejects enums for code that Node runs by stripping types. If a codebase already uses enums consistently, keep them; rewriting working code buys little.
When should I not turn on noUncheckedIndexedAccess?
Don't flip it on for a whole repository if nobody will fix the errors, because a build that stays red teaches people to ignore it. Enable it one package at a time and burn the errors down there. Index-heavy code such as array loops gets noisier, which is a real cost, but each error marks a lookup the code never checked.
Code review designed for human-written code catches only 47% of AI code issues. Here's the 3-layer review stack built for an AI-first world with measurable results.
A blanket ban on AI coding tools is as reckless as uncontrolled adoption. The RAPID decision framework helps engineering leaders choose the right control tier.
Most AI code quality advice fails in regulated industries. After consulting for fintech, healthtech, and automotive, here's the framework that passed 11 regulatory audits.
AI-heavy codebases have 3x the code duplication of non-AI codebases. After auditing 9 codebases, here's a 3-layer framework to prevent AI-introduced duplication.
After reviewing 500+ AI-generated snippets, I built the CRAFT prompt framework. Prompts with constraints produce acceptable code 82% of the time vs 45% without.
After 847 tracked AI pair programming sessions across 6 tools, here's what actually works and what wastes time. Data-driven results with a 3-question filter framework.