any vs unknown

September 23, 23

I know you are always confused with any VS uknown in typescript.

any vs unknown - cover

I like the statement from the famous TypeScript Cookbook -

Use `any` if you effectively want to deactivate typing; use `unknown` when you need to be cautious.

Let's understand a little bit more about both of them.

any

`any` is the most permissive type - it effectively turns off all type checking for all variables it is applied to - you can access any property without restriction. Similarly you can also assign any values to it.

const dwight: any = 'Dwight Schrute';

console.log(dwight.age);

unknown

`unknown` is a safer alternative when dealing with values of unknown types. It will still allow any values to be assigned to it, but typescript will require you to narrow its type before performing operations over it.

const dwight: unknown = 'Dwight Schrute';

// TypeError - 'dwight' is of type 'unknown'.
console.log(dwight.age);

// To fix this
if (dwight && typeof dwight === 'object' && 'age' in dwight) {
console.log(dwight.age);
}

The above `if` condition will narrow down the type of `dwight` and safely allow any value access on it.

Tip:

Use `any` when nothing works out and you just wanna get through, use `unknown` when you need to be extra cautious - like my boss always say.