TypeScript’s ‘any’ vs. ‘unknown’ Types and Their Proper Use
Don’t Sacrifice Code Safety for Flexibility
Table of contents
Since the introduction of the unknown
type in TypeScript, sometimes it might feel confusing when to use it and how.
On top of that, we have any
type, that is similar to the unknown
type, but the key difference is that the unknown
is type-safe.
This raises a question why do we even need any
type then?
Should we even use it?
We will answer all these questions and learn more about any
and unknown
types below in this article.
Understanding any
Type
If you are not familiar with any
type, the simplest explanation of what any
type is would be that it allows you to use variables without type-checking.
But isn't the whole point of using TypeScript is type checking you would ask?
And that’s a very good point.
Actually, using any
type should be avoided as much as possible as it can break your code at runtime. See the example below:
So when any
type is even used?
There are some use cases where any
type might be beneficial.
One of these cases is when migrating your code from JavaScript to TypeScript.
Understanding unknown
Type
unknown
type was introduced in TypeScript 3.0 and it’s a type-safe alternative of any
type.
But to use it you first have to narrow the type.
The code below is one of the ways how it can be done:
unknown
type is great when you are dealing with external data like APIs, user input, or third-party libraries where the type needs verification.
Quick Tip
As mentioned before, you should avoid using any
type as much as possible.
You can utilize compiler options like ‘strict’
and ‘noImplicitAny’
to catch unintentional use of any
.
Wrap Up
any
and unknown
types can be great tools in different scenarios.
The most important part is to know when to use each.
Understanding these two types deeply, can make you a better developer.