What is the difference between any and unknown in TypeScript? Why does the linter not complain about any, but requires type narrowing for unknown?
sobes.tech AI
Answer from AI
In TypeScript, any and unknown are types that can hold a value of any type, but they differ in safety and behavior:
-
anydisables type checking. You can do anything with a variable of typeanywithout compilation errors. This is convenient but dangerous, as it loses all type safety. -
unknownis a safer alternative toany. A value of typeunknowncan be assigned to any variable, but to use it as a specific type, you must first perform a type check (type narrowing). This forces explicit handling of possible types and prevents errors.
Why does the linter not complain about any, but require narrowing for unknown:
-
anyis considered "error suppression," and linters usually do not prohibit it but recommend avoiding it. -
unknownby design requires a check to ensure safety, so the linter enforces type narrowing before use.
Example:
let a: any = 10;
let u: unknown = 10;
// with `any`, you can do anything:
console.log(a.toFixed(2)); // no error
// with `unknown`, you need narrowing:
if (typeof u === 'number') {
console.log(u.toFixed(2)); // now safe
}