As I was saying in my last post, I am trying to avoid using the
any type as much as possible. Although I understand the need for skipping type checks, I think using
any defeats the whole purpose of Typescript. Luckily, at work I am also using Eslint so unless I disable some specific rules, I can't integrate
any in my code.
If you really need to skip type checking, you can use something that Typescript
3.0 introduced: the
unknown type. Unlike
unknown is safer to use in the sense that before actually doing something with data of this type, we must do some sort of checking, whereas
any has no restrictions.
Anything is assignable to unknown, but unknown isn't assignable to anything but
anywithout a type assertion or a control flow based narrowing. Likewise, no operations are permitted on an unknown without first asserting or narrowing to a more specific type.
What does that really mean? Let's take the examples bellow:
We see we can assign anything to a variable of type
unknown (I used just a few types to point this out). Now let's see what happens when we try to reassign
unknown to something that's not
Notice the following: we can assign whatever we want to variables of types
unknown. We can only reassign the
any type variable to whatever we want (in this case, a variable of type number). Trying to reassign
unknown to a variable of type
number will throw an error (as mentioned, it can only be reassigned to
On their own, variables of type
unknown are not very useful but when performing extra checks, they can be quite powerful. I am going to use an example in comparison with the
Looking at the code above, we have two variables, one of type
any, one of type
unknown. When trying to run the
.map() method on
variable_of_any_type, the editor doesn't complain, although it doesn't know if the variable is indeed of type array (and as we can see, it's not). We won't spot this until after compiling time when we'll get an error saying
Uncaught TypeError: variable_of_any_type.map is not a function.
When trying to do the same thing with the variable of type
unknown, the editor complains and says
Object is of type 'unknown'.. This means that it still doesn't know if it's an array so we must make an extra check. We do that on the next lines, we see that
variable_of_unknown_type is indeed an array, therefore we can perform the
.map() function on it.
Image source: ThisisEngineering RAEng/ @thisisengineering on Unsplash