DEV Community

Karishma Shukla
Karishma Shukla

Posted on โ€ข Edited on

8 5 3 3 3

'any' vs 'unknown' in TypeScript

When you start learning TypeScript, you will come across two types - "any" and "unknown"

any - The any type allows us to assign literally โ€œanyโ€ particular value to that variable, simulating what we know as plain JavaScript.

unknown - The unknown type is the type-safe counterpart of any. Anything is assignable to unknown, but unknown isn't assignable to anything but itself and any without a type assertion or a control flow based narrowing.

Let's understand with an example.



let age: number;
let userAge: any;

userAge = 'This is some age';
userAge = 20;

age = userAge;


Enter fullscreen mode Exit fullscreen mode

This code works! ๐ŸŽ‰
Type of userAge is any so it can be assigned any value - string, number etc.



let age: number;
let userAge: unknown;

userAge = 'This is some age';
userAge = 20;

age = userAge;


Enter fullscreen mode Exit fullscreen mode

The statement age=userAge gives an error.
The type is unknown so what is the problem here?
To assign an unknown value to a value with a fixed type, we have to do some quick type check!



let age: number;
let userAge: unknown;

userAge = 'This is some age';
userAge = 20;

if(typeof userAge === 'number') {
  age = userAge;
}


Enter fullscreen mode Exit fullscreen mode

And now this works too! ๐ŸŽ‰

When to use what?

You shouldn't use either of them. But if you really have to then unknown is a better choice if you know what you want to do with that value eventually.
I don't recommend using any - it takes away the actual essence of TypeScript!

Sentry blog image

How I fixed 20 seconds of lag for every user in just 20 minutes.

Our AI agent was running 10-20 seconds slower than it should, impacting both our own developers and our early adopters. See how I used Sentry Profiling to fix it in record time.

Read more

Top comments (3)

Collapse
 
johnkey profile image
INDERA SHAH โ€ข

๐Ÿ‘๐Ÿ‘๐Ÿ‘๐Ÿ‘

Collapse
 
jesusparra profile image
JesusParra โ€ข

Thanks, it was easy to understand!

Collapse
 
patrickcodes profile image
Nishant โ€ข

This is great ๐Ÿ‘๐Ÿ‘
Most of the blogs are too long to read. This explains it very quickly.
Thank you!

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs