Skip to content
Tutorials Center
My learning

Topics

TypeScript Reference ยท Concepts and Comparisons

any versus unknown in TypeScript

Compare any and unknown: what each allows, why unknown is the safe escape hatch, how to narrow it, and where any still appears.

Both any and unknown accept every value. The difference is what you may do afterwards. A value of type any switches the type checker off for that value: you can call it, index it, add to it and assign it anywhere, and nothing is verified. A value of type unknown is the opposite: you can hold it and pass it along, but you must narrow it before using it.

Prefer unknown for data whose shape you do not know. Use any only as a deliberate, short-lived workaround.

TypeScript
let a: any = "text";
let u: unknown = "text";
a.foo();      // compiles, fails at run time
// u.foo();   // error TS18046: 'u' is of type 'unknown'.

Try it

TypeScript any hides a bug, unknown forces a check

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

TypeScript Using unknown without narrowing

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Comparison

any unknown
Assign any value to it Yes Yes
Assign it to other types Yes (except never) Only to unknown and any
Property access, calls, arithmetic Allowed, unchecked Error until narrowed
Narrowing with typeof, in, guards Not needed Required
Spreads unchecked values Yes, it is contagious No
In unions any absorbs the other members unknown absorbs the other members, too
In intersections any & T is any unknown & T is T

Usage notes

  • any is contagious. Anything derived from an any value (property reads, call results) is also any, so one escape spreads through the code.
  • Narrow unknown with typeof, instanceof, in, equality, a custom type guard or a validation library; see unknown.
  • Catch clauses: with useUnknownInCatchVariables (part of strict), catch (e) gives unknown; see useUnknownInCatchVariables.
  • noImplicitAny makes accidental any an error; explicit : any remains allowed.
  • as any is the largest hammer. Often as unknown as T is more honest because it states the lie, but both bypass the check.
  • Generic constraints: T extends unknown is the default; T extends any has the same effect, but only unknown documents intent.
  • ESLint rules such as no-explicit-any and no-unsafe-* help find leaks.
  • Third-party JSON, fetch().json() and event data are classic places to choose unknown.