Sobes.tech
Middle

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:

  • any disables type checking. You can do anything with a variable of type any without compilation errors. This is convenient but dangerous, as it loses all type safety.

  • unknown is a safer alternative to any. A value of type unknown can 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:

  • any is considered "error suppression," and linters usually do not prohibit it but recommend avoiding it.

  • unknown by 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
}
What is the difference between any and unknown in… - sobes.tech