All academies
Roadmap/Expert

Level 18

Performance & Best Practices

Write TypeScript that stays fast to compile and safe to change: prefer inference with explicit boundaries, quarantine any, use unknown and satisfies, and structure types so the checker helps you instead of fighting you.

25 min read + quiz

Annotate Boundaries, Infer Internals

The highest-leverage habit in TypeScript is knowing where to write types. Annotate the boundaries — exported function signatures, public APIs, module edges — and let inference handle local variables and internals. Boundary annotations are documentation and contract; internal annotations are mostly noise that drifts out of date.

Explicit return types on exported functions have a second benefit: they localize errors. Without one, a mistake inside the function silently changes the inferred return type and errors appear at distant call sites; with one, the error points at the actual bug. They also measurably speed up type checking in large codebases because the compiler skips re-inference.

Conversely, do not annotate what inference already knows better. Writing const items: Array<string> = ['a'] adds nothing; writing const config = { retries: 3 } as const captures more precise literal types than any annotation you would write by hand.

// Boundary: explicit, documented, stable.
export function calculateDiscount(
  price: number,
  tier: "free" | "pro" | "enterprise"
): number {
  // Internals: inferred, low-noise.
  const rates = { free: 0, pro: 0.1, enterprise: 0.2 } as const;
  const rate = rates[tier]; // inferred: 0 | 0.1 | 0.2
  return price * (1 - rate);
}

Types at the edges, inference in the middle.

Taming any: unknown and Quarantine

any is not a type — it is an off switch. It silences checking on the value and on everything the value touches, and it spreads: one any parameter can quietly detype an entire call chain. Treat each any as a small hole in the hull.

unknown is the safe counterpart: it accepts any value but permits no operations until you narrow. Every place you receive data you do not control — JSON.parse, network responses, catch variables, message events — should produce unknown, followed by a type guard or schema validation.

You will not reach zero any in a real codebase, and that is fine. The goal is quarantine: confine any to the smallest possible scope (one line, one adapter function), convert to a real type immediately, and enable no-explicit-any lint warnings so new holes need justification. An any at a module boundary is a bug; an any inside a well-typed wrapper is a pragmatic tool.

// BAD: any spreads silently.
function processBad(data: any) {
  return data.user.name.first; // no checking anywhere
}

// GOOD: unknown forces validation at the boundary.
function processGood(data: unknown): string {
  if (
    typeof data === "object" &&
    data !== null &&
    "name" in data &&
    typeof (data as { name: unknown }).name === "string"
  ) {
    return (data as { name: string }).name;
  }
  throw new Error("Malformed payload");
}

unknown accepts everything but permits nothing until proven.

satisfies: Check Without Widening

The satisfies operator (TypeScript 4.9+) validates that an expression matches a type while keeping the expression's own, more precise inferred type. It resolves the old tension between annotating (safe but widened) and not annotating (precise but unchecked).

The canonical case is a config object. Annotate it as Record<string, string[]> and every property lookup returns string[] — you lose which keys exist. Use satisfies Record<string, string[]> instead, and the compiler still rejects wrong values, but keeps the literal keys and even tuple-ish precision of each entry.

Reach for satisfies whenever you think 'I want this checked against an interface, but I do not want to lose what the compiler already figured out': theme palettes, route tables, feature-flag maps, lookup dictionaries. It is check-only — no runtime cost, no type change.

type Palette = Record<string, [number, number, number] | string>;

const theme = {
  primary: [59, 130, 246],
  danger: "#ef4444",
} satisfies Palette;

// Precision preserved:
const r = theme.primary[0]; // number — compiler knows it's a tuple
const hex = theme.danger;   // string

// Still checked:
// const bad = { primary: true } satisfies Palette; // Error!

// With an annotation instead, theme.primary would be
// [number, number, number] | string and need narrowing every time.

satisfies validates the shape but keeps the precise inferred type.

Compiler Performance in Large Codebases

Type checking time is a real cost: it is your editor latency and your CI wall-clock. The biggest wins are structural. Explicit return types on exported functions stop inference from chasing deep call graphs. Prefer interfaces over large intersection chains — interfaces are cached by name, while anonymous intersections are re-expanded at each use.

Beware of huge unions and deeply recursive conditional types. A union of a few thousand string literals (say, generated from a database) can make every assignment involving it slow. If a type exists only to be looked up, a Record or a branded string often checks faster than a giant literal union.

Measure before optimizing: tsc --extendedDiagnostics shows where time goes, and tsc --generateTrace produces a trace you can open to find the specific types that explode. For monorepos, project references plus incremental builds keep rechecking proportional to what changed instead of the whole world.

// Slow pattern: anonymous intersections re-expanded everywhere.
type Entity = { id: string } & { createdAt: Date } & { owner: string };

// Faster: a named interface is cached by identity.
interface EntityFast {
  id: string;
  createdAt: Date;
  owner: string;
}

// Explicit return types stop deep inference chains:
export function buildIndex(items: EntityFast[]): Map<string, EntityFast> {
  return new Map(items.map((i) => [i.id, i]));
}

// Diagnose, don't guess:
//   npx tsc --noEmit --extendedDiagnostics
//   npx tsc --noEmit --generateTrace ./trace

Named interfaces and explicit boundaries keep checking fast.

Design Types for Change

Good TypeScript makes future edits safe. Model with discriminated unions and exhaustive switches so that adding a variant produces compile errors at every site that must handle it — the compiler becomes your refactoring checklist.

Derive types instead of duplicating them: keyof typeof for enums-as-objects, ReturnType for factory outputs, Pick and Omit for variations. Duplication is not just tedium — duplicated types drift, and drift produces the confusing 'two types with the same name are incompatible' errors that plague large apps.

Finally, resist cleverness. A type that takes minutes to understand costs every future reader those minutes. If a conditional type needs a comment longer than itself, a small amount of duplication or an extra explicit interface is often the better engineering choice. Types are code; readability rules apply.

const STATUSES = {
  active: "Active",
  suspended: "Suspended",
  closed: "Closed",
} as const;

// Derived — adding a status updates everything:
type Status = keyof typeof STATUSES; // "active" | "suspended" | "closed"

function label(status: Status): string {
  return STATUSES[status];
}

function nextAction(status: Status): string {
  switch (status) {
    case "active":
      return "none";
    case "suspended":
      return "review";
    case "closed":
      return "archive";
    default: {
      const unhandled: never = status; // new statuses break the build here
      return unhandled;
    }
  }
}

One source of truth; the compiler enforces every consumer.

Try it yourself

This lesson's example is preloaded in the playground — break it, fix it, extend it.

Open in playground

Check your understanding

Question 1 · Multiple choice

Why are explicit return types recommended on exported functions but not on every local variable?

Question 2 · Multiple choice

What is the key difference between any and unknown?

Question 3 · Predict the output

Using satisfies, what does this print?

const config = {
  port: 3000,
  host: "localhost",
} satisfies Record<string, string | number>;

const port = config.port;
console.log(typeof port, port + 1);

Question 4 · Find the error

This function type-checks but contains a latent bug that strict TypeScript was supposed to prevent. What went wrong?

function getTotal(response: any): number {
  return response.data.items
    .map((i: any) => i.price)
    .reduce((a: number, b: number) => a + b, 0);
}

Question 5 · True or false

For compiler performance, a named interface is generally cheaper than an equivalent chain of anonymous intersection types used in many places.