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:
-
anydisables type checking. A variable with typeanycan be assigned anywhere and used without restrictions. This reduces type safety. -
unknownis a safer alternative toany. A value of typeunknowncan only be assigned to a variable of typeunknownorany. To use anunknownvalue, 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.