Unions and Narrowing 28 exercises
explainer

Introducing the Unknown Type in TypeScript

In TypeScript, there's a special type called unknown. It represents something we don't know what it is, but we still want to keep type checking on it. The unknown type is unique because anything is assignable to it.

let input: unknown;

You can assign any value to unknown, s

Loading explainer

Transcript

00:00 Let's introduce a whole new type into our understanding of TypeScript. That is the unknown type. Anything is assignable to unknown. Unknown represents something that we just don't know what it is, but we want to keep type checking on it. And you can see that we can pass anything to it.

00:16 We can pass hello, a number, a Boolean, like an object. Anything whatsoever can be passed to unknown. And unlike any, which we've seen before, you can actually do type checking on this. We're going to look at how you can narrow this down later, but because input is of type unknown, we can't access any properties on it.

00:36 We can't do anything with it. We can pass it to other functions that expect unknown. So unknown is assignable to itself, but we have to narrow it before we can do anything with it. This is really, really useful when you have things coming into your application from outside sources. So for instance, JSON, that's coming from a webhook

00:55 or input from a form, let's say. Unknown is really, really useful in those situations. And unknown, it sits right at the top of our type hierarchy here. So we have, like, if we look at all of these values here, we've got a string down the left, so all sorts of objects here.

01:12 Strings, we have literals, which are assignable to strings, number literals, which are assignable to numbers, literal Booleans, et cetera, and null and undefined are all assignable to unknown. Unknown sits at the very top of the type hierarchy in TypeScript. It is the top type.

01:30 So if you think about anything in TypeScript, that all sits under the unknown umbrella. And this is really, really useful. We're going to look at the bottom type later, but having the idea that unknown sort of sits at the top, represents everything in TypeScript, is really important. And unknown is very different to any,

01:48 because if we put any inside here, then we wouldn't get any type checking whatsoever. Any doesn't really sort of sit in this type hierarchy. I'll show you a diagram of it later. But really, unknown is the way that if you want to represent something that's truly unknown in JavaScript, then unknown is the way to go.