Explainers

TypeScript: Switch or Lookup Object? Plus Infer from Keys

Published
Duration
Language
English

Watch on YouTube ↗

Summary

Two TypeScript habits for stricter checks. First, a lookup object as an alternative to a switch statement: end the object with satisfies Record of Status and string, and adding a member to the union without adding its entry becomes a compile error. A switch that returns a value also reports a missing case, but a lookup object works for handlers that return nothing too. Use a lookup for one plain value or handler per key; keep the switch when cases narrow to different payload shapes, fall through, or exit early. Second, infer from keys instead of passing a type by hand: a getter typed as K extends keyof Config, returning Config of K, gives get port as a number and rejects a misspelled key, while a getter that takes a caller-supplied type parameter accepts both mistakes. At the end, both ideas are combined in a handlers object and a dispatch function that checks the payload against the key.

Caveat: if the key can come from user input, check Object.hasOwn first, because a lookup object also has inherited properties such as constructor.

Every snippet was checked with tsc strict mode on TypeScript 7.0.2 and 5.9.3.

Chapters

  1. 0:00 Switch and lookup object: two ways
  2. 0:34 Infer from keys instead of type parameters
  3. 0:59 Both together

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. Here is a switch over a status. 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. A switch that returns a value catches this too; the lookup also covers handlers that return nothing. 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. Misspell the key, and that compiles too. Make the key the only argument. K extends keyof Config, and return Config of K.

Now get port is a number, get host is a string, and a typo in the key is an error. Combine them: a handlers object, and a dispatch function that checks the payload against the key. Let the compiler check the boring parts.

Sources

Credits and notes

  • Narrated with Phonon; motion in Remotion.

More in this series · Explainers