Unknown vs Any typescript

Both Unknown and any are different and have a different purpose in typescript.

If you are new to data types or unknown and any in typescript, feel free to check this post – Data types in typescript

If we do not know the actual type of a variable while decelerating it, then we use unknown.
On the other hand, while performing an operation on data, if you do not know the type of result then you can declare your result variable as any.

Difference between unknown and any in typescript –

The biggest difference between unknown and any in typescript is that –
any works in fully dynamic mode, means we can call any method or property to the any type and even if this method or property does not exist, still the typescript will not throw any compile-time error.
While we cannot do the same with the unknown.

Let’s take an example –

let myAnyVariable: any = 'This is some value';
myAnyVariable.Nitish();                     // No compile time error
console.log(myAnyVariable.NitishKaushik);   // No compile time error

let myUnknownVariable: unknown = 'This is some value';
myUnknownVariable.Nitish();                  // Compile time error
console.log(myUnknownVariable.NitishKaushik); // Compile time error

In the above example you can notice that any is not type-safe. You can even apply the methods or properties that don’t even exist in the application for the type.