Sobes.tech
Middle

What is 'unknown' in TypeScript and how does it differ from 'any'?

sobes.tech AI

Answer from AI

In TypeScript, unknown is a type that represents a value of an unknown type. It is more strict than any because with unknown, you cannot perform operations or assign it to other types without type checking.

Main differences between unknown and any:

  • any disables type checking, allowing you to do anything with the variable, which can lead to runtime errors.
  • unknown requires a type check or assertion before using the value, increasing code safety.

Example:

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

let c: number;

c = a; // OK, any can be assigned to any type

c = b; // Error: cannot assign unknown without checking

if (typeof b === 'number') {
  c = b; // OK, after type check
}

Thus, unknown is useful when you need to accept values of an unknown type but want to maintain type safety.