Avoid errors using unknown type

Kamran Ahmed
InstructorKamran Ahmed
Share this video with your friends

Social Share Links

Send Tweet

unknown is the type-safe counterpart of the any type. The main difference between unknown and any is that with any you can do anything with the variable with the type set as any; while the variable with the type unknown only allows you to assign it the values and perform equality checks i.e. ===, ==, !== and !=, for any other operation, you must either create a type guard or specify the type using val as SomeType.

You should prefer to use unknown over any whenever possible because it gives you the same flexibility of any when assigning values to the variables but you must specify the type while using the variable.

Kamran Ahmed: Let's say that we have a function called log, which is accepting a variable called val with the type any. Inside this function we can do anything with the val and TypeScript is not going to complain. We can call the string methods, let's say val.toUpperCase(). We can do the numerical operations, so let's say val + 20. We can also call the unknown methods, so let's say val.something.

If I call this method log with a number, let's say 5, even though TypeScript is not complaining here, when we've done this in the browser, JavaScript is going to break, because toUpperCase does not exist on the number type and also something does not exist on the number type.

TypeScript has another upper level type called unknown, which can be used as a replacement for any. I can put here unknown. The only thing you can do with the unknown type is assign it the value and put the equality checks. Let's say value == something or !== something.

For any other usage of the val type of unknown, you have to specify the type guard or the type first before you use it. In this case, if I have to perform the string operations on the val type unknown, I have to put the string type guard. I will have to do if (typeof val === 'string') then call the toUpperCase here, so in this case, the error goes away.

Inside this type guard, I can perform all the string operations on the val, but outside this type guard, I can't still do anything. Here I have to wrap this val in the brackets and call hasNumber() for it to be considered as a number. Either specify the type guard or you can put as and then the type that you want to consider it with.

Same for this one. Let's say that we have a type called Some which is having a method called something returning void and now we can specify it here on the val with val as Some and now we can call this something method onto the val.