Skip to content

TypeScript in Production: Concepts for Mid and Senior Engineers

The TypeScript concepts interviewers expect mid and senior engineers to apply in production: strictness, runtime validation, unions, generics and type safety at boundaries.

16 min read9 conceptsTechnical testsTypeScript in production

Interviewers who ask situational TypeScript questions are rarely checking whether you remember syntax. They want to see whether you know where the type system protects you and where it stops. Types are erased at runtime, so the hard problems sit at the edges: API payloads, database rows, error handling, and the places where someone wrote as to silence the compiler. This guide covers the ideas that come up again and again in production codebases. These include compiler strictness, validating untrusted data, modelling state with discriminated unions, narrowing, generics, derived types, escape hatches, branded types and module emit. Each concept includes a small invented example and the traps that turn a reasonable answer into a weak one.

Study order

If time is short, go in this order.

  1. Validating untrusted data at runtime boundaries

    Type erasure is the single most important production fact. Most situational questions come back to where untrusted data enters and how you check it.

  2. Strict compiler settings and what each flag buys you

    Every other guarantee depends on the compiler flags. You should be able to name them and explain how you would migrate a lax codebase.

  3. Discriminated unions and exhaustiveness checking

    This is the main modelling tool for state and API results, and the never check is a favourite review topic.

  4. any, unknown, type assertions and satisfies

    Knowing when any, as, ! and satisfies are acceptable separates careful engineers from those who silence the compiler.

  5. Narrowing, type predicates and assertion functions

    Narrowing explains most confusing compiler errors, and unsound predicates are a common hidden bug.

  6. Generics, constraints and keyof

    Shared utilities and library code depend on generics that keep the caller's types without casts.

  7. Deriving types with utility, mapped and conditional types

    Deriving DTOs from one source of truth prevents drift, and knowing the limits of Omit and Partial shows depth.

  8. Structural typing and branded types

    Structural typing is a frequent senior-level question, and brands are the standard answer to mixed-up IDs.

  9. Module emit, type-only imports and enums

    Build and packaging issues come up in production incidents, but interviewers ask about them less often than about type design.

Strict compiler settings and what each flag buys you

strict: true is a bundle of flags, not one check. It turns on strictNullChecks, noImplicitAny, strictFunctionTypes, useUnknownInCatchVariables and others. Without strictNullChecks, null and undefined are assignable to every type, so the compiler can't catch the most common production crash. A senior answer names the specific flags and the bugs each one prevents. Saying "we use strict mode" is not enough.

Some valuable flags sit outside strict. noUncheckedIndexedAccess makes arr[i] and record[key] return T | undefined, which matches what actually happens at runtime. exactOptionalPropertyTypes stops you from explicitly assigning undefined to an optional property. That matters when { discount: undefined } and {} mean different things to your PATCH handler.

On an existing codebase you can't flip everything on in one go. The usual approach is to enable a flag, count the errors, and fix them directory by directory. Some teams use a separate stricter tsconfig for new folders, or a tool that tracks the error count so it only goes down.

JSON

{
  "compilerOptions": {
    "target": "ES2022",
    "module": "NodeNext",
    "moduleResolution": "NodeNext",
    "strict": true,
    "noUncheckedIndexedAccess": true,
    "exactOptionalPropertyTypes": true,
    "noImplicitOverride": true,
    "noFallthroughCasesInSwitch": true,
    "verbatimModuleSyntax": true,
    "skipLibCheck": true
  }
}

A strict baseline for a Node service. strict covers null safety and implicit any. The extra flags cover indexing, optional properties and override safety.

Traps

  • Assuming strict includes noUncheckedIndexedAccess. It doesn't, and indexed reads stay typed as always present.
  • Turning strictness on and then silencing thousands of errors with ! and as any. That makes the code look typed while it is not.
  • Forgetting that skipLibCheck hides type errors inside .d.ts files, including your own generated declarations.

Validating untrusted data at runtime boundaries

TypeScript types disappear after compilation. When a webhook, an HTTP response, a message queue or JSON.parse hands you data, the compiler has no idea what it contains. JSON.parse returns any, so writing const order: Order = JSON.parse(body) is an unchecked claim, not a guarantee.

The production pattern is to type the incoming value as unknown and run it through a parser. The parser checks the shape and returns a properly typed value, or it throws. Inside the trusted core you can then rely on the types. Schema libraries such as Zod, Valibot or io-ts generate both the validator and the type from one definition. A hand-written parser works the same way.

In an interview, say where you put the boundary: request handlers, queue consumers, config loading and third-party SDK responses. Also say what happens on failure. A 400 response, a dead-letter queue and a crash at startup are all reasonable for different boundaries. Silently continuing with half-valid data is not.

TypeScript

type RefundEvent = { kind: "refund"; orderId: string; amountCents: number };

function isRecord(v: unknown): v is Record<string, unknown> {
  return typeof v === "object" && v !== null && !Array.isArray(v);
}

function parseRefundEvent(input: unknown): RefundEvent {
  if (!isRecord(input)) throw new Error("payload must be an object");
  const { kind, orderId, amountCents } = input;
  if (kind !== "refund") throw new Error(`unexpected kind: ${String(kind)}`);
  if (typeof orderId !== "string" || orderId.length === 0) {
    throw new Error("orderId must be a non-empty string");
  }
  if (typeof amountCents !== "number" || !Number.isInteger(amountCents) || amountCents <= 0) {
    throw new Error("amountCents must be a positive integer");
  }
  return { kind, orderId, amountCents };
}

const rawBody = '{"kind":"refund","orderId":"ord_7731","amountCents":2599}';
const event = parseRefundEvent(JSON.parse(rawBody));
console.log(event.amountCents / 100); // 25.99

A webhook handler for a payments provider. The value stays unknown until every field has been checked.

Traps

  • Casting JSON.parse(...) as Order and treating that as validation.
  • Validating only the outer object and trusting nested arrays or optional fields.
  • Typing third-party API responses by hand and never checking them. The provider can change a field from number to string without telling you.
  • Defining a schema and a separate interface that slowly drift apart. Derive the type from the schema instead.

Discriminated unions and exhaustiveness checking

A discriminated union models a value that can be in one of several distinct states. Each state carries only the data that makes sense for it. A shared literal field such as status or kind lets the compiler narrow to the right variant in a switch or if.

The alternative is one wide object full of optional fields, like { status: string; ticketCode?: string; reason?: string }. That shape allows impossible combinations, such as a cancelled booking with a ticket code. It also forces null checks everywhere. Unions make illegal states unrepresentable.

Pair unions with an exhaustiveness check. If the default branch assigns the value to never, adding a new variant later turns every unhandled switch into a compile error. You find the gaps at build time instead of in production.

TypeScript

type Booking =
  | { status: "held"; holdExpiresAt: Date }
  | { status: "confirmed"; ticketCode: string }
  | { status: "cancelled"; reason: string };

function assertNever(value: never): never {
  throw new Error(`Unhandled variant: ${JSON.stringify(value)}`);
}

function describeBooking(b: Booking): string {
  switch (b.status) {
    case "held":
      return `Seat held until ${b.holdExpiresAt.toISOString()}`;
    case "confirmed":
      return `Ferry ticket ${b.ticketCode}`;
    case "cancelled":
      return `Cancelled: ${b.reason}`;
    default:
      return assertNever(b);
  }
}

console.log(describeBooking({ status: "confirmed", ticketCode: "FRY-0412" }));

Ferry seat bookings. If you add a refunded variant, describeBooking stops compiling until you handle it.

Traps

  • Using a default that returns a fallback string. That silently swallows new variants instead of failing the build.
  • Typing the discriminant as string instead of a literal union, which stops narrowing from working.
  • Destructuring the discriminant into a separate variable too early. Narrowing through destructured fields only works in some cases, so switch on b.status directly when in doubt.

Narrowing, type predicates and assertion functions

Narrowing is how TypeScript refines a broad type into a specific one through control flow. It understands typeof, instanceof, in, equality checks, truthiness and discriminant fields. When those aren't enough, you write a user-defined type predicate (v is T) or an assertion function (asserts cond). An assertion function narrows everything after the call.

Predicates are trusted, not checked. If isAdmin(u): u is Admin returns true for the wrong input, the compiler believes it anyway. Treat every predicate as security-sensitive code: keep it small, test it, and make it check every property the target type relies on.

Two behaviours catch people out. Narrowing on a mutable variable or a property is reset inside callbacks, because the compiler can't know when the callback runs. Since TypeScript 5.5, simple filters such as xs.filter(x => x !== undefined) infer a predicate automatically. Older code often needs an explicit isDefined helper.

TypeScript

interface Sensor { id: string; lastReadingC?: number }

function isDefined<T>(value: T | null | undefined): value is T {
  return value !== null && value !== undefined;
}

function assert(condition: unknown, message: string): asserts condition {
  if (!condition) throw new Error(message);
}

const sensors: Sensor[] = [
  { id: "greenhouse-1", lastReadingC: 21.4 },
  { id: "greenhouse-2" },
  { id: "greenhouse-3", lastReadingC: 19.8 },
];

const readings: number[] = sensors.map((s) => s.lastReadingC).filter(isDefined);
const first = readings[0]; // number | undefined with noUncheckedIndexedAccess
assert(first !== undefined, "no sensor has reported yet");
console.log(first.toFixed(1)); // narrowed to number

Greenhouse sensors. A generic predicate cleans the array, and an assertion function narrows the first element.

Traps

  • Writing a type predicate that checks one field and claims the whole type.
  • Expecting narrowing of this.user or a let variable to survive inside a setTimeout or .forEach callback.
  • Declaring an assertion function as an arrow function without an explicit type annotation. Assertion signatures need an explicitly typed function or method to take effect.
  • Using truthiness to narrow numbers or strings, which also drops 0 and "".

Generics, constraints and keyof

Generics let a function keep the caller's type instead of flattening it. The key test is whether a type parameter links two or more positions, such as an input and an output, or two inputs. If it appears only once, you usually don't need a generic. A plain parameter type is clearer.

Constraints (T extends ...) state the minimum a type must have while keeping everything else. Compare latest(items: { updatedAt: Date }[]) with a generic version. The first returns the bare constraint type and loses the caller's fields. The generic version returns the caller's full type. K extends keyof T combined with the indexed access T[K] is the standard way to write type-safe property access.

Inside generic bodies the compiler is careful, sometimes annoyingly so. Reaching for as T to get past an error usually means the signature is wrong. Fix the constraint or use overloads rather than casting.

TypeScript

interface Invoice { id: string; totalCents: number; paid: boolean; updatedAt: Date }

function pluck<T, K extends keyof T>(rows: readonly T[], key: K): T[K][] {
  return rows.map((row) => row[key]);
}

function latest<T extends { updatedAt: Date }>(items: readonly T[]): T | undefined {
  let best: T | undefined;
  for (const item of items) {
    if (!best || item.updatedAt > best.updatedAt) best = item;
  }
  return best;
}

const invoices: Invoice[] = [
  { id: "inv_1", totalCents: 12000, paid: true, updatedAt: new Date("2024-03-01") },
  { id: "inv_2", totalCents: 4500, paid: false, updatedAt: new Date("2024-03-09") },
];

const totals = pluck(invoices, "totalCents"); // number[]
const newest = latest(invoices);               // Invoice | undefined, not just { updatedAt }
console.log(totals, newest?.id);

Invoice helpers. keyof keeps property access type-safe, and the constraint keeps the full Invoice type in the result.

Traps

  • Adding type parameters that appear only once. They add noise and can make inference worse.
  • Using as T inside a generic function to silence an error, which usually hides a real unsoundness.
  • Constraining with T extends object when the code actually needs specific fields.
  • Expecting the compiler to infer a literal type where it widens. Use a const type parameter (TS 5.0+) when you need literals preserved.

Deriving types with utility, mapped and conditional types

In a production codebase most types should be derived from a few sources of truth rather than written out twice. Pick, Omit, Partial, Required, Readonly, Record, ReturnType and Awaited cover most needs. A create payload is the entity without its id. A patch payload is a Partial of the editable fields.

Mapped types ({ [K in keyof T]: ... }) transform every property, and key remapping with as can rename or filter keys. Conditional types with infer pull types out of other types, such as the element type of an array or the resolved value of a promise.

Know the limits as well. Partial is shallow. Omit on a union does not distribute, so it collapses the union to the keys all members share. Conditional types distribute over naked unions, which is sometimes exactly what you want and sometimes a bug. Very clever types slow the compiler and produce unreadable errors, so stop where readability drops.

TypeScript

interface Employee {
  id: string;
  name: string;
  salaryCents: number;
  managerId: string | null;
}

type EmployeeCreate = Omit<Employee, "id">;
type EmployeePatch = Partial<Omit<Employee, "id">>;

type Getters<T> = {
  [K in keyof T & string as `get${Capitalize<K>}`]: () => T[K];
};
type EmployeeGetters = Getters<Pick<Employee, "name" | "salaryCents">>;
// { getName: () => string; getSalaryCents: () => number }

type ElementOf<T> = T extends readonly (infer U)[] ? U : never;
type Row = ElementOf<Employee[]>; // Employee

type DistributiveOmit<T, K extends PropertyKey> = T extends unknown ? Omit<T, K> : never;

const patch: EmployeePatch = { salaryCents: 820000 };
console.log(patch);

HR service types derived from one Employee interface, plus a distributive Omit for unions.

Traps

  • Applying Omit to a discriminated union and losing the variant-specific fields. Use a distributive version instead.
  • Assuming Partial<T> makes nested objects optional too.
  • Forgetting that T extends X ? A : B distributes over unions. Wrap it as [T] extends [X] to stop that.
  • Writing deeply recursive types that slow the build or hit instantiation depth limits.

any, unknown, type assertions and satisfies

any switches type checking off, and it spreads. Anything you read from an any is also any. unknown is the safe counterpart: you can assign anything to it, but you can't use it until you narrow it. Under strict, catch variables are unknown, because JavaScript lets you throw any value, not only Error objects.

Type assertions (x as T) and the non-null assertion (x!) are promises you make to the compiler, and nothing checks them at runtime. Use them sparingly and close to the place where you know the fact you're asserting. Prefer a narrowing check whenever one is cheap.

satisfies (TS 4.9+) checks that a value conforms to a type without widening it to that type. That is the right tool for config objects and lookup tables. You get an error for a missing or misspelled key, and the specific type of each property is kept.

TypeScript

type RouteValue = string | ((id: string) => string);

const routes = {
  home: "/",
  invoice: (id: string) => `/invoices/${id}`,
} satisfies Record<string, RouteValue>;

console.log(routes.invoice("inv_42")); // OK: invoice keeps its function type

// With an annotation instead, routes.invoice would be RouteValue and not callable:
// const routes: Record<string, RouteValue> = { ... };

async function loadQuota(): Promise<number> {
  try {
    const raw: unknown = JSON.parse('{"limit": 10}');
    if (typeof raw === "object" && raw !== null && "limit" in raw && typeof raw.limit === "number") {
      return raw.limit;
    }
    throw new Error("invalid quota payload");
  } catch (err: unknown) {
    const message = err instanceof Error ? err.message : String(err);
    console.error(`quota load failed: ${message}`);
    return 0;
  }
}

loadQuota().then(console.log);

satisfies keeps precise property types. unknown forces a check before use, including in catch.

Traps

  • Using as to fix a type error that is really a design problem. The error usually comes back as a runtime crash.
  • Chaining as unknown as T to force an incompatible cast. Reviewers should treat that as a red flag.
  • Accessing err.message in a catch block without checking err instanceof Error.
  • Annotating a config object with a wide type and losing the literal keys or function types that satisfies would have kept.

Structural typing and branded types

TypeScript compares types by shape, not by name. Two interfaces with the same fields are interchangeable, and so is every string. In a system with customer IDs, order IDs and currency codes all typed as string, nothing stops you passing an order ID where a customer ID belongs. The arguments line up, the code compiles, and the wrong record gets refunded.

Branded (or nominal) types add a phantom property that exists only in the type system. A plain string is no longer assignable to CustomerId. The only way to get one is through a constructor function that validates the raw value. That moves validation to a single place and documents intent in every signature.

The brand costs nothing at runtime, but it also gives no runtime protection. Values that cross a serialization boundary come back as plain strings and must go through the constructor again. Structural typing also explains excess property checks: they only apply to fresh object literals, so the same extra field passed through a variable is allowed.

TypeScript

declare const brand: unique symbol;
type Brand<T, B extends string> = T & { readonly [brand]: B };

type CustomerId = Brand<string, "CustomerId">;
type OrderId = Brand<string, "OrderId">;

function toCustomerId(raw: string): CustomerId {
  if (!/^cus_[a-z0-9]{8}$/.test(raw)) throw new Error(`bad customer id: ${raw}`);
  return raw as CustomerId;
}

function toOrderId(raw: string): OrderId {
  if (!/^ord_[a-z0-9]{8}$/.test(raw)) throw new Error(`bad order id: ${raw}`);
  return raw as OrderId;
}

function refundOrder(orderId: OrderId, customerId: CustomerId): string {
  return `refund ${orderId} for ${customerId}`;
}

const customer = toCustomerId("cus_a1b2c3d4");
const order = toOrderId("ord_z9y8x7w6");
console.log(refundOrder(order, customer));
// refundOrder(customer, order); // compile error: arguments swapped

Customer and order IDs share a runtime representation but can't be swapped at compile time.

Traps

  • Scattering as CustomerId across the codebase instead of keeping the cast inside one validating constructor.
  • Using a plain string property such as __brand that could clash with real data. A unique symbol key avoids that.
  • Expecting a brand to survive JSON.stringify or a database round trip.
  • Relying on excess property checks to reject extra fields when the object comes from a variable rather than a literal.

Module emit, type-only imports and enums

Most production builds no longer use tsc to emit code. esbuild, swc, Vite or Bun strip types one file at a time, without the full program. That is why isolatedModules and, in newer setups, verbatimModuleSyntax matter. They forbid patterns a single-file transpiler can't handle and force import type for imports that exist only as types, so those imports are removed cleanly. In that setup tsc --noEmit becomes your type check in CI, separate from the build.

Regular enum declarations generate runtime objects, and numeric enums accept any number. const enum is inlined by tsc but breaks or behaves differently under isolated transpilers. Many teams prefer an as const object plus a derived union type. It gives the same autocomplete, works with any transpiler and matches plain JSON values.

If you publish a library, ship .d.ts files (declaration: true) and set exports and types in package.json. Check both ESM and CommonJS consumers. Module resolution settings such as NodeNext require explicit .js extensions in relative imports.

TypeScript

// currency.ts
export const Currency = {
  EUR: "EUR",
  USD: "USD",
  GBP: "GBP",
} as const;

export type Currency = (typeof Currency)[keyof typeof Currency]; // "EUR" | "USD" | "GBP"

export interface Price {
  amountCents: number;
  currency: Currency;
}

// checkout.ts (with verbatimModuleSyntax and NodeNext)
// import { Currency } from "./currency.js";
// import type { Price } from "./currency.js";

export function formatPrice(p: Price): string {
  return new Intl.NumberFormat("en-GB", { style: "currency", currency: p.currency })
    .format(p.amountCents / 100);
}

console.log(formatPrice({ amountCents: 1999, currency: Currency.GBP })); // £19.99

An as const object with a derived union replaces an enum. Type-only imports are erased cleanly by any transpiler.

Traps

  • Assuming the bundler type-checks. esbuild and swc strip types without reporting errors, so CI needs a separate tsc --noEmit.
  • Using const enum across package boundaries or with isolated transpilers, where it may not be inlined.
  • Relying on numeric enums for validation. const s: Status = 42 compiles for numeric enums in older TypeScript versions.
  • Omitting .js extensions in relative imports under NodeNext, which compiles differently from what Node resolves at runtime.

Common questions

Short answers to the usual doubts.

Should I use interface or type alias?

Both work for object shapes. Interfaces can be extended and merged through declaration merging, which is useful for augmenting library types. They also tend to give clearer error messages on large object hierarchies. Type aliases are required for unions, mapped types, conditional types and tuples. A common team rule is interfaces for public object contracts and type aliases for everything else. Being consistent matters more than which rule you pick.

Does TypeScript make runtime tests unnecessary?

No. The compiler checks that the code is internally consistent with its declared types. It can't check that those declarations match real data, and it says nothing about business logic. Tests still cover behaviour, edge cases and the parsers at your boundaries. Strong types mainly remove the tests that only check shapes and null handling.

How do I handle a third-party library with missing or wrong types?

Look for a maintained @types package first. If the types are wrong, add a local declaration file or a module augmentation that fixes only what you use. Wrap the library behind a small typed adapter so the rest of the codebase never sees the bad types. Avoid spreading any from the library into your own modules.

Is `any` ever acceptable in production code?

Occasionally. Common cases are a temporary migration step, or a deliberately untyped low-level helper where unknown would force pointless casts. Keep it local, explain it in a comment, and make sure it doesn't leak through return types. Lint rules such as no-explicit-any with justified exceptions help keep it visible.

Now, practise it

Put it to work straight away.

Tests, exercises and problems that use what you've just read.

Next guide3 of 7 · Languages and runtimesPython in Production: Concepts for Mid and Senior InterviewsRead the next one