DEV Community

Cover image for Typescript - why to use "unknown" instead of "any"

Typescript - why to use "unknown" instead of "any"

Arika O on June 02, 2020

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 chec...
Collapse
 
gabbersepp profile image
Josef Biehler •

Nice. Did not know that feature!

Collapse
 
zerquix18 profile image
I'm Luis! \^-^/ •

So it was unknown for you???

ok I'll leave myself

Collapse
 
arikaturika profile image
Arika O •

Hope it helped :).

Collapse
 
ishansrivastava profile image
Ishan Srivastava •

unknown is just pessimistic 'any' 🙈. With any , ts is like "maybe it is of type array, who knows?", and with unknown it is like "dude, I am not taking any risks 😇".

Collapse
 
po5i profile image
Carlos V. •

Best explanation ever

Collapse
 
arikaturika profile image
Arika O •

Hehe, nice analogy :).

Collapse
 
terkwood profile image
Felix Terkhorn •

Thanks for the lesson. Your examples made this easy to understand, and I'm now motivated to use unknown the next time I start to reach for any! 🚸

Collapse
 
arikaturika profile image
Arika O •

Yes, why not? We indeed need to make some extra checks but since it's safer I believe it's worth it. Thank you for your input!

Collapse
 
attkinsonjakob profile image
Jakob Attkinson • • Edited

For situations where defining the type is not possible, I'd like to use the lazy gradual typing. Meaning, I have a global type alias TODO that's the same as any.

declare type TODO = any;
Enter fullscreen mode Exit fullscreen mode

While it's just a "hack", I do like it and it does come in handy from time to time. Some details.

However, the unknown solution you proposed seems much better overall.

Collapse
 
arikaturika profile image
Arika O •

Never thought about it, nice :D. Does it do anything else besides tricking the compiler?

Collapse
 
bradtaniguchi profile image
Brad •

I've ran across unknown when interacting with some libs but never understood what it meant in comparison to any. Now I know thanks!

Collapse
 
arikaturika profile image
Arika O •

I've rarely seen it in the wild too, I know what you mean. Glad that it helped :).

Collapse
 
ryzhov profile image
Aleksandr N. Ryzhov •

Taken it, very Thanks

Collapse
 
arikaturika profile image
Arika O •

You're welcome :).