Why we should use type unknown over any in Typescript?

One thing that has been buzzing around the TypeScript community for a while now is the question of the true nature of any and unknown. Sure, they help if you want to bypass type checking in TypeScript, but is one better than the other? Let's find out.

A closer look at TypeScript's any type

First, let's take a look at what any does in TypeScript. The any type is a powerful way of working with existing JavaScript, allowing us to bypass type checking on a per-file basis.

let myvariable: any = 4;
myvariable = "maybe a string instead";
myvariable = false; // okay, definitely a boolean

While it offers flexibility, using any can have unwanted effects on your codebase and effectively eliminate the benefits of using TypeScript.

Understanding TypeScript's unknown type

Introduced in TypeScript 3.0, unknown was designed to be a safer and more explicit alternative to any.
If you assign a value to a variable of unknown type, the compiler won't let you perform any arbitrary operations on it, nor will it let you pass it to a function. Here's an example.

let myvariable: unknown = 4;
myvariable = "maybe a string instead";
myvariable = false; // okay, definitely a boolean

let myvariableStr: string = myvariable;  
// Error: Type 'unknown' is not assignable to type 'string'

Why we should choose unknown over any

The unknown type is a much safer option than any. This is because unknown forces developers to do a proper type check before operating on values.

function customFunc(value: unknown) {
  if (typeof value === 'string') {  // Type assertion/guard
    console.log(value.toUpperCase());  // Now we can invoke string method
  }
}

Unknown encourages better coding habits and brings to light the true essence of TypeScript, purposeful and explicit typing.

In conclusion

In conclusion, while any serves a purpose in TypeScript, unknown is a safer and more robust alternative that promotes better coding practices. It is therefore recommended that developers use unknown in situations where they would otherwise use any.