The `any` type is like giving your variable permission to be anything - it disables TypeScript's type checking for that variable completely. It's your emergency escape hatch when you're working with dynamic data or third-party libraries. `unknown` is the safer alternative - it says "I don't know what type this is yet, but let's check before we use it."
`any` vs `unknown`
Use `any` when you need maximum flexibility, like working with dynamically evaluated data or untyped APIs. Use `unknown` when you want to maintain type safety while being open to different types. The key difference is that variables marked as `any` can be used without type checking, while `unknown` requires you to check the type first before using it.
// any type - disable type checking
let flexible: any = "I can be anything";
flexible = 42;
flexible = { name: "Alice" };
flexible.someProperty; // OK, even if it doesn't exist
// unknown type - requires type checking
let uncertain: unknown = "I need checking";
// uncertain.someProperty; // Error - need to check type first
if (typeof uncertain === "string") {
console.log(uncertain.toUpperCase());
} else if (typeof uncertain === "number") {
console.log(uncertain.toFixed(2));
}
// Exception for dynamic data
const rawData: any = JSON.parse(response);
const value = rawData.result;
Try it Yourself โ