This video is available to students only

Unknown and Never Type

In this lesson, we're going to study the unknown and never type in TypeScript

Unknown type#

You are almost done with the basics of TypeScript. There is something else I want you to know. I'm talking about the Unknown type. Unknown type is the type-safe counterpart of any. Anything is assignable to unknown, but unknown isn't assignable to anything but itself and the any type. Let me give you an example. Let's create a variable, hola, and assign type unknown to it. I'm gonna create another variable hallo, which is hello in German, and assign a type string to it. if I say hola = hallo, it's acceptable because we can assign anything to type unknown, but it's not possible the other way round. If I try to assign hola to hallo, we see an error; it saysType 'unknown' is not assignable to type 'string'. If hola were of type any, you could assign it to any variable, so let's change the type to any. See? The error's gone. So just keep in mind that anything is assignable to unknown, but unknown isn't assignable to anything but itself and type any.

Likewise, no operations are permitted on an unknown without first asserting or narrowing to a more specific type. Let me give you an example. Let's say I want to assign the unknown type to a string. In this case, I'll have to narrow it down to do that, so let's change hallo to a string again. Right now, it's complaining, but if I narrow it down; let's say, if typeof hola is string, then assign it to a string; now, it's possible. In short, unknown type is a stricter any type, which can only be assigned to itself or the any type and you can assign it to any variable, but any type can be assigned to anyone, and anything can be assigned to the any type.

Start a new discussion. All notification go to the author.