This page looks best with JavaScript enabled

unknown vs. any in Typescript

 ·   ·  ☕ 1 min read

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.

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

unknown seems to do the same thing.

1
2
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.

1
2
3
4
5
6
7
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.

Stay in touch!
Share on

Prashanth Krishnamurthy
WRITTEN BY
Prashanth Krishnamurthy
Technologist | Creator of Things