Skip to the content.

Chapter 10: Soundness, Escape Hatches and Staying Safe

Runnable examples: examples/ch10-soundness-and-escape-hatches.ts

A sound type system guarantees that if a program type-checks, values always have their declared types at runtime. TypeScript is not sound, on purpose: its design goals favor productivity and compatibility with existing JavaScript over a complete guarantee. Knowing exactly where the gaps are is what lets you rely on it.

1. Types are erased

TypeScript types do not exist at runtime. Node’s type stripping, bundlers and tsc all remove them. So:

function parseUserUnsafe(json: string): User {
  return JSON.parse(json) as User; // compiles, checks nothing
}

Anything coming from outside your program (HTTP bodies, files, environment variables, localStorage, message queues) is unknown in reality, whatever its annotation says. Validate it:

function parseUser(json: string): User {
  const data: unknown = JSON.parse(json);
  if (typeof data === "object" && data !== null &&
      "id" in data && typeof data.id === "number" &&
      "name" in data && typeof data.name === "string") {
    return { id: data.id, name: data.name };
  }
  throw new TypeError("Invalid user JSON");
}

For larger shapes, a schema validation library that also produces the TypeScript type avoids writing checks twice.

2. any is contagious

function fromLegacy(): any { return { id: "not-a-number" }; }
const user: User = fromLegacy(); // no error

any turns off checking where it appears and everywhere it flows. Common sources you might not notice: JSON.parse, untyped libraries, catch (e) without useUnknownInCatchVariables (part of strict), and as any added to silence one error.

Prefer unknown: it accepts any value but forces you to narrow before use.

3. Unchecked indexing

Without noUncheckedIndexedAccess, list[0] on a string[] has type string, even for an empty array. With the flag (enabled in this repository), it is string | undefined, which matches reality. The flag adds some friction and catches a common class of crashes.

4. Assertions are promises you make

Use them sparingly, close to the reason they are true, ideally with a comment explaining why.

5. Branded types: adding nominal typing where it matters

Because typing is structural, UserId and OrderId defined as number are interchangeable, which allows real bugs (loadOrdersFor(orderId)). A brand adds a phantom property that only exists at the type level:

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

type UserId = Brand<number, "UserId">;
type OrderId = Brand<number, "OrderId">;

function toUserId(n: number): UserId {
  if (!Number.isInteger(n) || n <= 0) throw new RangeError("UserId must be a positive integer");
  return n as UserId;
}

Now a plain number or an OrderId cannot be passed where a UserId is required. The only way to get a UserId is through the constructor function, which is also the natural place for runtime validation. Branded types work well for IDs, validated strings (emails, slugs), units (meters versus feet) and sanitized HTML.

6. Declaration merging

Interfaces with the same name in the same scope merge into one:

interface Settings { theme: string }
interface Settings { fontSize: number }
// Settings has both properties

Libraries use this deliberately so users can extend types (for example adding fields to a request object or a global Window). It can also surprise you when a global interface with a common name merges with yours; modules (files with import or export) keep your declarations local.

7. Prefer satisfies over as for checking values

const route = { path: "/admin", auth: true } satisfies Route; // checked
const hidden = { path: "admin" } as unknown as Route;          // unchecked, wrong at runtime

satisfies reports mistakes; as hides them.

A safety checklist for real projects

Setting or habit Why
"strict": true Enables strictNullChecks, strictFunctionTypes, noImplicitAny, useUnknownInCatchVariables and more
"noUncheckedIndexedAccess": true Index access includes undefined
"exactOptionalPropertyTypes": true Missing and undefined properties differ
Lint against any, non-null assertions and unsafe casts Keeps escape hatches visible in code review
Validate all external data at the boundary Types are erased at runtime
Readonly arrays in read-only APIs Avoids the array covariance hole
Property syntax for callback types Avoids method parameter bivariance
Brands for IDs and validated values Adds nominal safety where mix-ups are costly
Exhaustive switches with assertNever New union members cause compile errors, not silent bugs

Check yourself

  1. Why is JSON.parse(text) as User dangerous even though it compiles?
  2. What is the difference between unknown and any for code that uses the value?
  3. Why does a brand need a constructor function?
Answers 1. The cast checks nothing; the parsed value can have any shape at runtime. 2. `any` allows everything without checks; `unknown` requires narrowing before any use. 3. Plain values are not assignable to the branded type, so the constructor (with a cast inside) is the single, validated entry point.

Back to the table of contents.