DEV Community

Cover image for Stop drifting around in the dark when using "any" and "unknown" TypeScript types
Gianluca La Manna for This is Learning

Posted on

Stop drifting around in the dark when using "any" and "unknown" TypeScript types

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
Enter fullscreen mode Exit fullscreen mode

Imagine if you want to access a single prop, for example, lastname
We will do something like this:

const lastname =  person.lastname
Enter fullscreen mode Exit fullscreen mode

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
}
Enter fullscreen mode Exit fullscreen mode

Another right case is when we want to handle an error

try {
 ...something
} catch (err: unknown) { }
Enter fullscreen mode Exit fullscreen mode

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)
}
Enter fullscreen mode Exit fullscreen mode

Or when you want to do this (here it's allowed):

const person: any

person.trim()
Enter fullscreen mode Exit fullscreen mode

while here is not allowed:

const person: unknown

person.trim() // ❌ Error
Enter fullscreen mode Exit fullscreen mode

instead, you have to do:

const person: unknown

if(typeof person === 'string') person.trim()
Enter fullscreen mode Exit fullscreen mode

That's all. Bye guy 👋🏻

Top comments (1)

Collapse
 
pengeszikra profile image
Peter Vivo

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.