Sobes.tech
Middle

What is the difference between unknown and any in TypeScript?

sobes.tech AI

Answer from AI

In TypeScript, any and unknown are types that can contain values of any type, but there are important differences:

  • any disables type checking. A variable with type any can be assigned anywhere and used without restrictions. This reduces type safety.

  • unknown is a safer alternative to any. A value of type unknown can only be assigned to a variable of type unknown or any. To use an unknown value, you must first check its type or cast it to the required type.

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 forces the developer to explicitly check types, increasing code safety, while any disables all checks.

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