The Pragmatic TypeScript Patterns I Actually Use in Production

· 3 min read

Most TypeScript advice falls into one of two extremes: beginner tutorials explaining basic interfaces, or academic demonstrations of type-level arithmetic that look brilliant in a tweet but cause your IDE language server to crash in production.

When you're building products end to end, the goal of TypeScript isn't to prove a theorem. The goal is to make invalid states unrepresentable and catch human mistakes before they reach a customer.

Here are the pragmatic patterns that have saved me the most time and caught the nastiest bugs in production.

1. Branded Types for Primitive Identifiers

In a typical web application, database IDs, session tokens, and external references are all strings:

function transferTeamOwnership(teamId: string, newOwnerUserId: string) {
  // ...
}

const currentUserId = "usr_102";
const teamId = "team_994";

// Compiles completely fine, but swaps the arguments!
transferTeamOwnership(currentUserId, teamId);

TypeScript uses a structural type system, which means any string satisfies any other string. You can prevent entire classes of security vulnerabilities and silent bugs by "branding" primitives with zero runtime cost:

declare const brand: unique symbol;

export type Brand<T, B> = T & { readonly [brand]: B };

export type UserId = Brand<string, "UserId">;
export type TeamId = Brand<string, "TeamId">;

function transferTeamOwnership(teamId: TeamId, newOwnerUserId: UserId) {
  // ...
}

// Error: Argument of type 'string' is not assignable to parameter of type 'TeamId'.
transferTeamOwnership(currentUserId, teamId);

You create small constructor helpers to cast at your I/O boundaries (like route params or database queries):

export const asUserId = (id: string) => id as UserId;
export const asTeamId = (id: string) => id as TeamId;

Once validated at the boundary, you can pass IDs across hundreds of services without ever confusing an entity ID with a user ID again.

2. Eliminating Impossible States with Discriminated Unions

A common anti-pattern in frontend components or API responses is tracking separate boolean flags:

type AsyncState<T> = {
  isLoading: boolean;
  isError: boolean;
  error?: Error;
  data?: T;
};

This simple shape permits impossible states:

Instead, model states as an explicit state machine using a discriminated union:

type AsyncState<T> =
  | { status: "idle" }
  | { status: "loading" }
  | { status: "success"; data: T }
  | { status: "error"; error: Error };

Now, TypeScript refuses to let you read state.data unless you have verified that state.status === "success". You don't need optional chaining or guesswork.

3. Exhaustiveness Checking with assertNever

When switching over a discriminated union or an enum, you want the TypeScript compiler to throw an error immediately if someone adds a new variant without handling it everywhere:

export function assertNever(value: never): never {
  throw new Error(`Unhandled discriminated union member: ${JSON.stringify(value)}`);
}

Use it in the default case of your switch statements:

type Plan = "free" | "pro" | "team";

function getMonthlyCredits(plan: Plan): number {
  switch (plan) {
    case "free":
      return 100;
    case "pro":
      return 5000;
    case "team":
      return 25000;
    default:
      // If someone adds "enterprise" to Plan, this line will fail compilation!
      return assertNever(plan);
  }
}

This turns every future refactor or feature addition into a compiler-guided checklist.

4. Single Source of Truth with Inferred Schema Types

Duplicating TypeScript interfaces and runtime validation schemas (like Zod) guarantees they will drift out of sync eventually. Always define your runtime schema first and infer the static TypeScript type directly from it:

import { z } from "zod";

export const UpdateProfileSchema = z.object({
  displayName: z.string().min(2).max(50),
  bio: z.string().max(280).optional(),
  notifyOnRelease: z.boolean().default(true),
});

// Single source of truth:
export type UpdateProfileInput = z.infer<typeof UpdateProfileSchema>;

Use the inferred type in your frontend forms and the schema parser in your backend route handlers. If a field changes, TypeScript breaks in every consumer before you even run the code.

Summary

The best TypeScript code feels lightweight. It doesn't fight the developer with unreadable generics, and it doesn't force you to write assertions. Focus on boundary validation, branded IDs, and discriminated unions—they provide 95% of the safety with none of the complexity.

Thoughts? Email me at sudarshan096k@gmail.com.

GitHub
LinkedIn
X