DEV Community

Cover image for Typescript - Tips & Tricks - any vs. unknown
Luca Del Puppo for This is Learning

Posted on • Updated on

Typescript - Tips & Tricks - any vs. unknown

Hi guys, today I'll talk about the difference between any and unknown.

Any
Any type is a particular type in typescript.
If you use this type, the compiler doesn't check your code, and the power is in your hands, but from great powers comes great responsibilities. In this case, the compiler doesn't check your code, but maybe your code could have bugs; these bugs will most likely be found by a user during his operations.

Unknown
Unknown type is another particular type in typescript, it's similar to Any type but it helps us to prevent bugs at build time.
The unknown type helps us to force the check of its type before using it.

Now let's turn to some examples.

Any Type

let myAny: any = true
myAny.trim().reverse().split(',');
let myAnyNumeric: number = myAny;
const sum = myAnyNumeric + 3;
Enter fullscreen mode Exit fullscreen mode

In this case, we can see a problem right away; in the second line, we try to call the trim method on a boolean type. This code at runtime throws an exception, but we need to run this code to detect this bug.
In the third line instead, I set a boolean type to a numeric type, and in the next line, I add three to this value.
Ok, I think you have understood the possible problems you could have if you overuse any type.

Unkown Type

let myUnknown: unknown = true;
myUnknown.trim(); // Property 'trim' does not exist on type 'unknown'.ts(2339)
let myAnyNumeric: number = myUnknown; // Type 'unknown' is not assignable to type 'number'.ts(2322)
if (typeof myUnknown === 'string') myUnknown.trim();
if (typeof myUnknown === "number") {
  let myAnyNumeric: number = myUnknown;
  const sum = myAnyNumeric + 3;
}
Enter fullscreen mode Exit fullscreen mode

In this example, we can see the power of using unknown type instead of any type.
This type doesn't stop the compiler check but it helps us to check our type to prevent bugs at runtime.
Typescript understands what you want to do, and it indicates you the correct way to prevent bugs.

After this post, I think that from now on you will prefer to use unknown instead of any and I know the reason ;)

That's all!
Bye-bye guy!!

Top comments (0)