Sobes.tech
Junior — Middle

What is the difference between the 'any' and 'unknown' types in TypeScript in terms of their usage and type safety?

sobes.tech AI

Answer from AI

The any type in TypeScript disables type checking for a variable, allowing it to be assigned values of any type and to perform any operations without compile-time errors. This is convenient but reduces type safety, as errors may only manifest at runtime.

The unknown type can also hold a value of any type, but you cannot perform operations on it or assign it to other types without explicit type checking or casting. This makes unknown safer, as it forces the developer to explicitly handle the data type before use.

Example:

let a: any = 5;
a = "string"; // allowed
let b: number = a; // also allowed, but may cause runtime error

let u: unknown = 5;
u = "string";
// let c: number = u; // compile error
if (typeof u === "number") {
  let c: number = u; // safe
}

In summary, any is "disabling" typing, while unknown is a safe alternative that requires type checking before use.