Glossary / unknown versus any

unknown versus any

unknown and any can each hold values of any JavaScript type, but they have opposite safety behavior. unknown requires narrowing or assertion before most operations; any disables checking and propagates through expressions, allowing unchecked operations to spread.

Assignability and use

A value of any type can be assigned to unknown. An unknown value cannot be assigned to a specific type or operated on without a guard or assertion. any is assignable both to and from nearly every type and suppresses many diagnostics. This makes unknown the safer type for untrusted inputs and generic catch values.

function parse(value: unknown): string | undefined {
  if (typeof value === 'string') return value;
  return undefined;
}

An assertion from unknown is not a runtime check; it simply tells the compiler to trust the programmer. any can be useful at narrow, temporary boundaries for untyped libraries or incremental migration, but should be contained and replaced with declarations or validation.

Engineering guidance

Enable noImplicitAny, use unknown for JSON and uncertain values, and narrow through schemas, guards, or discriminants. Avoid allowing an any return to flow into core domain logic. In catch clauses, modern TypeScript can type errors as unknown; check instanceof Error or handle non-Error thrown values.

Interview questions

  1. Can you call a method on unknown? Not without narrowing or asserting.
  2. Why is any dangerous? It disables checks and can contaminate later expressions and assignments.
  3. Does as User validate? No, it is compile-time only.
  4. What should represent unvalidated JSON? unknown until runtime validation succeeds.
  5. When can any be acceptable? At a narrow interoperability/migration boundary with a plan to contain it.

References