Typescript: Difference between unknown vs any

Both unknown and any are similar in a way but they are disimilar in a way too. Sounds confusing? Lets check out

How they are similar?

//any case
let user:any
user = 'abcd';
or
user = {name: 'abcd'}

Both the above cases stand `true` and it work seamlessly in Typescript.

How they are different ?

let user: any = 'abcd;
console.log(abcd.add()) // Error: Object is of type 'unknown'. error but runtime error

Above, will work at compile time but will break at runtime. This is very `dangerous and harmful`. There is no way for developer to know how the code will behave at run time.

let user:unknown = 'abcd';
console.log(abcd.add()); // This will result in compile time error

Above, error will be highlighted by the IDE and there will be a compile time error too.

How we can work with unknown?

There are couple of ways. idea is to narrow the type down of unknown

  1. Type casting
let user: unknown;
(user as string).toString()

2. Type Guard

let user: unknown;
if(typeof user === 'string') {

--

--

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store