Exhaustive Switch Statements - TypeScript

David Taing

6/24/2023

Screenshot of Exhaustive Switch Statement Code Snippet

TS Playground:

View a live demo here: https://lnkd.in/gMH7u—i


Description:

Assigning the switch expression to a never-typed variable will cause a compile-time error.

Explaination:

I like to think of types as boxes.

At the start, we have a union of the strings "Zurich", "Oslo" and "London". These are the potential types inside the “location” box.

As we move down the switch statement and handle each case, we pull out these options out of the box.

  1. We go from a box that can have "Zurich", "Oslo" or "London",
  2. Then either "Oslo" or "London",
  3. Then "London" only,
  4. And finally this leaves us with a never type

This is really useful if you plan on adding more options to your union types. If we forget to pull out a option out of the Locations box, we’ll get a compile-time error.

So we’ll know straightaway that we’ve make a mistake.

That’s an introduction to Type Narrowing in TypeScript.


Credit:

Christian Woerz

Deep Dive into Advanced TypeScript: A Live Coding Expedition
NDC Oslo 2023

Video

Start: https://lnkd.in/gt7ePcAx
End: https://lnkd.in/gzbwcvBR

If you want to see more of this. Please let me know!


Written By David Taing

Dave is an ex-Property Manager turned Fullstack TypeScript Engineer. He mostly spends his time gluing APIs together at work, building side-projects, regularly going to tech meetups, and sharing the things he learns online.