Repaso
EspaƱol
Frontend & WebAdvancedFE-20

In TypeScript, unknown vs any?

Options

  1. They are identical in behavior and in safety
  2. unknown must be narrowed; any turns off checks (Correct option)
  3. any is safer than unknown when typing data
  4. unknown is only used to type caught errors

Answer

unknown must be narrowed (typeof, instanceof, type guards) before use; any disables type checking

Why

any switches off type checking: you can do anything with it, and mistakes are only found at runtime.

unknown means 'I don't know the type yet': TypeScript will not let you use it until you check it, e.g. if (typeof x === "string").

Use unknown for data from outside (JSON, API responses) and validate it.

Remember

Prefer unknown over any.

Key terms

Practice this question in Repaso