Explainers

TypeScript as const, satisfies and Branded Types: Zero Runtime Cost

Published
Duration
Language
English

Watch on YouTube ↗

Summary

Stricter types at zero runtime cost. This short explainer covers three TypeScript tools that exist only at compile time: as const (TypeScript 3.4), which turns an array of roles into a readonly tuple of literals; satisfies (TypeScript 4.9), which checks a value against a type without widening it, unlike an annotation such as Record of string and Route; and branded types, a community pattern, not an official TypeScript feature, where a UserId stops being an OrderId. At the end the compiled JavaScript is compared with the untyped version: it is identical.

Every snippet was checked with TypeScript 5.9.3 and 7.0.2 (tsc strict mode, zero errors).

Chapters

  1. 0:00 Three tools, zero runtime cost, and as const
  2. 0:22 satisfies: check without widening
  3. 0:39 Branded types: UserId is not OrderId
  4. 0:52 The emitted JavaScript is identical

Transcript

Text of the video's narration.

Three TypeScript tools that make your types stricter, and cost nothing at runtime: as const, satisfies, and branded types. As const keeps the exact value. An array of roles stops being a string array and becomes a readonly tuple of the literals admin, editor, viewer.

Index typeof roles with number, and you get a union of exactly those three. Satisfies checks a value without widening it. Annotate a routes object as Record of string and Route, and the keys become plain strings, so routes dot about still compiles.

Use satisfies, and every entry is checked, while the keys stay precise: home and user. Branded types are a community pattern, not a language feature. Intersect string with a readonly brand property, and a UserId is no longer an OrderId.

Pass the wrong one, and it does not compile. Compile it, and the emitted JavaScript is identical to the untyped version. Plain arrays, plain objects, plain strings. Stricter types, zero runtime cost.

Sources

Credits and notes

  • Narrated with Phonon; motion in Remotion.

More in this series · Explainers