any
and unknown
are data types in Typescript. You can assign either of them to anything that you want. For example:
let a: any = [];
let b: unknown = 968;
What differentiates any
from unknown
? If you use any
, type checking is skipped and you can access the value:
let x: any;
x = 5;
console.log(any.toFixed()) //5
unknown
on the hand is type safe. That is, it is checked before the value is accessed. If we use the previous example but with unknown
this time, we will get an error if we don’t do a check on the type of value that will be accessed or try to specify the type:
let x: unknown;
x = 5;
if (typeof(x) === "number")
console.log(x.toFixed()); //5
Without doing a check on the type of value that will be accessed, your IDE or editor will place a red squiggly line under x and show you the following message once you hover your mouse over ‘x’:
let x: unknown;
x = 5;
console.log(x.toFixed()); //Property 'toFixed' does not exist on type 'unknown'