The never Type and switch Statements
Learn about the never type and how it's used with switch statements in TypeScript.
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:
// Define a function that always throws an errorfunction alwaysThrows() {// Throw an error with a specified messagethrow new Error("this will always throw");// Return a value, but it will never be reached because of the thrown errorreturn -1;}alwaysThrows();
Function throwing error
-
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 ...