Explainers · Short
Switch or lookup object in TypeScript?
- Published
- Duration
- Language
- English
Transcript
Text of the video's narration.
Two TypeScript habits for stricter checks: a lookup object as an alternative to switch, and inferring from keys. A lookup object is another way: an object that satisfies Record of Status and string. Add paused to the union, and the object stops compiling.
Use a lookup for one plain value or handler per key. Keep the switch for narrowing to different shapes, fallthrough, or early exits. Second habit. This getter takes its type from the caller. Ask for port as a string, and it compiles, even though port is a number.
Make the key the only argument. K extends keyof Config, and return Config of K. Now a typo in the key is an error. Let the compiler check the boring parts.
Sources
- TypeScript handbook, Generics (type parameters in generic constraints) typescriptlang.org
- TypeScript handbook, Keyof type operator typescriptlang.org
- TypeScript handbook, Narrowing (exhaustiveness checking with switch) typescriptlang.org
- TypeScript 4.9 release notes (the satisfies operator) typescriptlang.org
- MDN, Object.hasOwn developer.mozilla.org
Credits and notes
- Narrated with Phonon; motion in Remotion.



