Improve your switch cases with TypeScript
In this tutorial, you will learn how to improve your switch statements and fix certain errors in TypeScript. The article provides tips and tricks, as well as a final code example. Some key takeaways include setting `noImplicitReturns` to `true`, creating a switch case for every valid value, defining a custom return type, and adding a default case to handle unexpected values.
In this tutorial Benny shows you simple techniques on how to improve your switch statements. Using the tips and tricks from the video, you will never miss a switch case again. You will also learn how to fix error TS2322, TS2366 and TS7030.
Contents
Video
Errors fixed in the video:
TS2322: Type 'undefined' is not assignable to type 'number'.
TS2366: Function lacks ending return statement and return type does not include 'undefined'.
TS7030: Not all code paths return a value.
Final Code
Summary
- Set
noImplicitReturns
totrue
in yourtsconfig.json
- Create a switch case for every valid value
- Define a custom return type to narrow your function's return values
- Create a
default
case to handle values that might slip in through using your TypeScript code from JavaScript code