In TypeScript, unknown vs any?
Options
- They are identical in behavior and in safety
unknownmust be narrowed;anyturns off checks (Correct option)anyis safer thanunknownwhen typing dataunknownis 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.