Q4: What is the difference between `any` and `unknown` types?

Difficulty:EasyTopic:Type Safety

any disables type checking entirely, turning off compile-time safety. You can access arbitrary properties, call them as functions, or assign them to any target type.

unknown is the type-safe counterpart of any. It represents any value, but TypeScript prevents you from performing arbitrary operations on an unknown variable until you perform explicit type checking or narrowing.

any vs unknown Behavior
let valueAny: any = "hello";
valueAny.foo.bar(); // Compiles fine, runtime crash!

let valueUnknown: unknown = "hello";
// valueUnknown.trim(); // Error: Object is of type 'unknown'.

if (typeof valueUnknown === "string") {
  console.log(valueUnknown.trim()); // Valid! Narrowed safely.
}
💡 unknown forces developer verification before property access, preventing accidental runtime exceptions.
Key Takeaways
  • Prefer unknown over any when working with dynamic or unexpected values.
  • unknown requires explicit narrowing before property access.