Unions and Narrowing 28 exercises
solution

Empty Arrays and the Never Type in TypeScript

When hovering over shoppingCart.items inside the call to console.log, we can see that it is inferred as an array of type never:

console.log(shoppingCart.items);

// hovering over items shows:
(property) items: never[]

// hovering over shoppingCart shows:
const shoppingCart: {
  items:
Loading solution

Transcript

00:00 Okay, why is this error occurring? Argument of type string is not assignable to parameter of type never. A never has appeared inside our application. How is this possible? Well, if we hover over shoppingcart.items here, we'll see that items is actually inferred as an array of never. We'll hover over shoppingcart,

00:19 we can see it's an object with items, never array. Well, why is this happening? It's because we haven't given shoppingcart.items a type here and an array that contains nothing in TypeScript is considered by default, a never array, right? We can technically add things to it. It's not a tuple, we can change it,

00:38 but it's never containing anything. This is the type that TypeScript gives it. So this is a little awkward. It means that when we then push to that items thing here, it means that sure, we can't push string, we can't push number, can't push anything to it because nothing is assignable to never. So how do we, of course, if we did this,

00:57 if we did like items, we start with a pair in there, let's say, now items will be inferred as an array of strings here. And so we'd be able to push strings to it because it would understand, okay, items is supposed to be an array of strings, we're good to go. But if we start off empty, it's basically never. How do we do this? How do we get around it?

01:16 Well, we can give it a type. So we can say this is a shoppingcart type and then say type shoppingcart equals items string array here and of course an array which contains nothing is assignable to string array here. So we're all good. Now, everything just works. This is nice.

01:34 But this is another way that never can kind of sneak into your code a little bit. It's just through the empty array type, which by default in TypeScript is inferred as never array.