I often see junior developers overuse the any
type. They also rarely use unknown
, or don't use it at all.
We define the Differences
The main difference between these two types is:
any
: Can be anything
unknown
: It's similar, but you must check or assert the type before using it
So, the question is: When should we use these types?
"Use" any
Probably an answer we already have: Don't use any type or avoid using it as much as possible.
This is because if we use any, we're saying: this object can be anything:
const person: any
Imagine if you want to access a single prop, for example, lastname
We will do something like this:
const lastname = person.lastname
At runtime, if we are lucky, we won't have any problems. But this means that if the lastname props do not exist, we have a runtime error, probably in production.
We want to avoid it. It's the same if we use vanilla JS, because we don't define a type.
Use unkwnown
But when we have to use unknown?
let b: unknown = 42;
let c: number = b; // ❌ Error
if (typeof b === "number") {
let c: number = b; // ✅ ok
}
Another right case is when we want to handle an error
try {
...something
} catch (err: unknown) { }
Sometimes we don't know the type of error, and here we use unknown
In the above example:
try {
...something
} catch (err: unknown) {
if(err instanceof Error) {
console.error(err)
}
Or when you want to do this (here it's allowed):
const person: any
person.trim()
while here is not allowed:
const person: unknown
person.trim() // ❌ Error
instead, you have to do:
const person: unknown
if(typeof person === 'string') person.trim()
That's all. Bye guy 👋🏻
Top comments (1)
I prefer JSDoc instead of TS, because that is not force to declare type as the tru nature of JS, but keep the option to use it ( same complexity as TS ). That is not force to use any which is really useless thing.