Explainers · Short

Switch or lookup object in TypeScript?

Published
Duration
Language
English

Watch on YouTube ↗

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

Credits and notes

  • Narrated with Phonon; motion in Remotion.

More in this series · Explainers