Learn TypeScript

Using the never type

Using the never type

In this lesson, we'll learn about the never type and how it is different from the void type.

How never is different from void

We are going to explore the never type in the exercise below.

TypeScriptOpen exercise in CodeSandbox

The code contains an infinite loop where a message is output to the console.

🤔

What is the return type of the keepLogging function?

🤔

Why isn't the return type void?

Use cases for never

Let's look at a different example where the never type is useful.

  • Copy and paste the following code into the editor:
1type Status = "Pending" | "Working" | "Complete";
2
3function doSomeAction(status: Status) {
4 switch (status) {
5 case "Pending":
6 // some code
7 break;
8 case "Working":
9 // some code
10 break;
11 case "Complete":
12 // some code
13 break;
14 }
15}
16
17doSomeAction("Pending");

We haven't covered the syntax on line 1 yet. This creates a string type that can hold "Pending", "Working", or "Complete". Don't worry if this doesn't make sense because we will cover it in detail later in the course.

The code also contains a function containing a switch statement that does different things depending on the different values for the status parameter.

  • Let's add a new cancelled status:
type Status = "Pending" | "Working" | "Complete" | "Cancelled";

Wouldn't it be nice if TypeScript reminded us that we need to handle this new status in the doSomeAction function switch statement? Well, we can use the never type to do this.

  • Add the following the function:
function neverReached(never: never) {}

This function takes in a parameter of type never. So, it's a function that, in theory, should never be reached in the code.

🤔

How can we use the neverReached function in a default branch of the switch statement in doSomeAction?

Notice that we now get a type error in the default branch of the switch statement.

Never error

  • Implement the cancelled switch statement branch:
case "Cancelled":
// some code
break;

The type error will disappear.

Neat!

Summary

The never type is used to represent a type of value that will never occur. It is useful to explicitly flag areas of code that shouldn’t be reached. It is also useful when creating conditional types, which we will learn about later in this course.

Further information about the never type can be found in the TypeScript handbook.

In the next lesson, we’ll learn about a type that we can use as an alternative to any.

© 2023 Carl Rippon
Privacy Policy
This site uses cookies. Click here to find out more