Sobes.tech
Middle+

What is the difference between any and unknown in TypeScript?

sobes.tech AI

Answer from AI

In TypeScript, any and unknown are types that allow working with any values, but there are important differences:

  • any disables type checking. A variable of type any can be assigned anything, and any operations can be performed on it without compilation errors. This reduces type safety.

  • unknown is a safer alternative to any. It can also hold any value, but before using the value, you need to perform a type check or cast it to the required type. The compiler will not allow direct use of an unknown type variable without checking.

Example:

let a: any = 10;
let u: unknown = 10;

let num1: number = a; // OK
// let num2: number = u; // Compilation error

if (typeof u === 'number') {
  let num2: number = u; // OK after check
}

Thus, unknown helps write safer code by forcing explicit type handling, whereas any is a "least resistance" path without type control.

What is the difference between any and unknown in… - sobes.tech