The never Type and switch Statements
Explore the never type in TypeScript and its role in preventing logic errors. Learn how to use never with functions that never return and in switch statements to ensure all enum cases are handled, improving code safety and reliability.
We'll cover the following...
The never type
The final primitive type in the TypeScript collection is a type of never. This type is used to indicate instances where something should never occur. Even though this
may sound confusing, we can often write code where this occurs.
Consider the following code:
-
We have a function named
alwaysThrows()on lines 2–8, which will, according to its logic, always throw an error. -
Remember that once a function throws an error, it will immediately return, and no other code in the function will execute. This means that line 7, which returns a value of
-1, will never execute.
This is where the never type can be used to guard against ...