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 (4)
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.
Yeah, it’s probably just a different approach. However, I believe TypeScript is more expressive and precise. In the end, the most important thing is to avoid runtime errors.
JSDoc can fully replace TS even capability of avoid runtime errors, because the end of the day still TS behind it:
dev.to/pengeszikra/jsdoc-evangelis...
Yes, I get it. The all projects (js typified) that I saw in my career are in ts. As I say above, probably is different way. In my opinion I don't like the comment style and then ts handle a lot of stuff such as type inference. But here the purpose of this article was different. However I will read your article, because I'm curious.