Typescript: Difference between unknown vs any
1 min readMay 20, 2022
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'}// unknown case
let user: unknownuser = '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
- Type casting
let user: unknown;
(user as string).toString()
2. Type Guard
let user: unknown;
if(typeof user === 'string') { user.toString();
}