Better Programming

Advice for programmers.

Follow publication

Member-only story

Stop Using Switch in TypeScript — 3 Alternatives To Use Instead

You can avoid the switch statement, as TypeScript has its own versions

Fernando Doglio
Better Programming
Published in
6 min readApr 7, 2021
Man looking inside vending machine
Photo by Victoriano Izquierdo on Unsplash.

What’s wrong with the following code?

You can very well say “nothing.” That would be a valid answer. But this code can be considered a code smell if you find it as part of a larger code base where there is a lot more logic around and inside it. Truth be told, switch statements aren’t that great.

With a switch statement, you’re creating a huge block of code that has to be executed serially, checking one condition after the next one. Its syntax allows for problems such as forgetting to write a break clause and causing multiple cases to be executed accidentally. You don’t want to use a switch statement if you can avoid it, but what are the alternatives?

Depending on the language you’re using, you’ll have different options at your disposal. Given that we’re dealing with TypeScript (and therefore, JavaScript), we can mix and match. Here are my three favorite ways of avoiding switch

Create an account to read the full story.

The author made this story available to Medium members only.
If you’re new to Medium, create a new account to read this story on us.

Or, continue in mobile web

Already have an account? Sign in

Fernando Doglio
Fernando Doglio

Written by Fernando Doglio

I write about technology, freelancing and more. Check out my FREE newsletter if you’re into Software Development: https://fernandodoglio.substack.com/

Responses (24)

Write a response