Unions and Narrowing 28 exercises
explainer

Introducing the `never` Type in TypeScript

Consider a function that doesn't return anything:

const getNever = () => {
  // This function never returns!
};

When checking the type of this function, TypeScript will infer that it returns void, indicating that it essentially returns nothing.

// hovering over `
Loading explainer

Transcript

00:00 Let's talk about a type called never we have introduced the unknown type so far and the unknown type is like the top type in TypeScript. And if you're thinking, okay, I see what's at the top, what's at the bottom?

00:14 Well, never is the bottom type in TypeScript, never represents something that can never happen. And this means that let's say this function here, this function, like if we just had nothing happen inside this get never function,

00:29 then it would return, right? It would do something and it would return void, indicating that it returns nothing essentially. But there's got to be something stronger than that. And what happens if you throw an error inside that function?

00:43 Well, now that function never returns. And so if we hover over get never, you can see that it has a function just returning never. And this is really interesting. So never being a type that's just available in TypeScript has some really weird implications. You cannot assign anything to never. So we have a function here, which has an input of never.

01:04 You can't assign anything to it except for never itself. And weirdly enough, never is assignable to anything. So we have a bunch of, let's say, strings and numbers and booleans and arrays down the bottom. And this get never function, we can assign it to anything.

01:22 What? How on earth would that work? Well, let's take a look at this big old diagram here. We have the same diagram as we had before explaining unknown, except we've added never at the bottom.

01:35 And never really truly is the bottom type here. We can assign never to string if we want to, to 123, to boolean, to anything. Never sits right at the bottom. And it means that anything that you have in TypeScript can never be assigned to never, because it's something that can never happen.

01:55 So when you think about never, and as we sort of approach it in the next exercises, think about this diagram. Think about unknown being the thing right at the top, where you can assign anything to unknown, but you can't go the other way. And never, it's kind of like the reverse, where it sits right at the bottom.

02:10 You can assign it to anything, but nothing can be assigned to it because it can never happen. Confusing, I know, but think about this hierarchy and things in the next few exercises will feel a lot smoother.