TypeScript Developer interview question · Most asked

Explain `any`, `unknown` and `never`.

Summary

any disables type checking for a value; unknown is the type-safe top type: anything can be assigned to it, but you must narrow it before use; never is the bottom type for values that never occur (functions that throw, exhaustive checks).

Longer Answer

Prefer unknown for untrusted input (JSON, catch variables with useUnknownInCatchVariables) and narrow with typeof, instanceof or schema validation. any spreads silently through code and should be rare (lint with no-explicit-any). never is useful in exhaustive switch statements: assigning the remaining value to never makes the compiler error when a new union member is added.

Code Example

function parse(json: string): unknown {
  return JSON.parse(json);
}

const data = parse('{"name":"Ana"}');
// data.name;  // Error: 'data' is of type 'unknown'
if (typeof data === "object" && data !== null && "name" in data) {
  console.log((data as { name: string }).name);
}

function assertNever(x: never): never {
  throw new Error(`Unexpected: ${JSON.stringify(x)}`);
}

Key Points

  • any: opt out of checking (contagious)
  • unknown: must narrow before use
  • never: impossible values, exhaustiveness
  • Prefer unknown for external data

Comparison / Tradeoffs

Type Assign anything to it? Use without checks?
any Yes Yes (unsafe)
unknown Yes No, narrow first
never No N/A

More most-asked TypeScript Developer questions

← All TypeScript Developer questions