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:
-
anydisables type checking. A variable of typeanycan be assigned anything, and any operations can be performed on it without compilation errors. This reduces type safety. -
unknownis a safer alternative toany. 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 anunknowntype 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.