Avatar ·

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

Hi! I recently started learning TypeScript and came across the `any` and `unknown` types. They both seem to allow storing anything, but I don't fully understand the difference between them and when to use which.\n\nHere's an example that confuses me. I have a function that receives data from an API, and I don't know what exactly will come:\n\n```typescript\nfunction processData(data: any) {\n console.log(data.toUpperCase()); // Works, but if data is not a string - crashes at runtime\n}\n```\n\nIf I replace `any` with `unknown`:\n\n```typescript\nfunction processData(data: unknown) {\n console.log(data.toUpperCase()); // Compilation error: Object is of type 'unknown'\n}\n```\n\nSo with `unknown`, the code doesn't even compile. Why is `unknown` needed if it only gets in the way? I've heard that `unknown` is