...

/

The never Type and switch Statements

The never Type and switch Statements

Learn about the never type and how it's used with switch statements in TypeScript.

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 error
function alwaysThrows() {
// Throw an error with a specified message
throw new Error("this will always throw");
// Return a value, but it will never be reached because of the thrown error
return -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 ...