Avatar ·

Types `unknown` and `any` in TypeScript: what's the difference and when to use which?

Hi everyone! I recently started learning TypeScript and came across two types that at first glance seem very similar: `any` and `unknown`. Both allow storing values of any type, but I feel there is some important difference between them that I'm missing. For example, I'm writing a function that receives data from an API. I don't know in advance what exactly will come — it could be an object, a string, or a number. Here's how I'm doing it now: ```typescript function processData(data: any) { console.log(data.toUpperCase()); // Works without errors, but can crash at runtime } ``` But if I try to use `unknown`, I get an error: ```typescript function processDataSafe(data: unknown) { console.log(data.toUpperCase()); // Error: Object is of type 'unknown' } ``` Why