unknown vs. any in Typescript

Why use unknown when we have any in Typescript?

Type inferences are powerful and allows us to do magic when we don’t know types.

const i: any = 1;
console.log(i);
// 1

unknown seems to do the same thing.

let x: unknown = 1;
console.log(x);

So, which to use where?

Let us extend the previous examples to put that question to rest. Consider what happens when you try to do any operation on the type.

const i: any = 1;
console.log(i + 1);
//2

const x: unknown = 1;
console.log(x + 1);
// error TS2365: Operator '+' cannot be applied to types 'unknown' and '1'

unknown applies itself enthusiastically to equality operations, asserts and checks, but not for any other operations.

This makes sense because we do not know the type of the particular variable and cannot subject it to operations or methods that expect a specific type.

Using unknown lends itself to better type safety and is recommended to be used for unknown data types.

comments powered by Disqus