Explainers · Short
Stricter TypeScript types, zero runtime cost
- Published
- Duration
- Language
- English
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
- TypeScript 3.4 release notes (const assertions) typescriptlang.org
- TypeScript 4.9 release notes (the satisfies operator) typescriptlang.org
- Handbook, Everyday Types (type assertions are removed by the compiler) typescriptlang.org
- Handbook, Type Compatibility (structural typing) typescriptlang.org
- TypeScript Deep Dive, Nominal Typing (community write-up of the brand pattern) basarat.gitbook.io
Credits and notes
- Narrated with Phonon; motion in Remotion.



