What is the useUnknownInCatchVariables option in TypeScript?
Why Interviewers Ask This
Candidates at the intermediate level are expected to not only know this concept but explain the trade-offs involved. Interviewers use this question to see if you can reason about design decisions, not just recall facts.
Answer
useUnknownInCatchVariables (TypeScript 4.0+, enabled by strict mode) changes the default type of catch clause error variables from any to unknown. Before: try { ... } catch (error) { error.message; /* valid, error was any */ }. With this option: catch (error) { error.message; /* TypeScript error! error is unknown */ }. You must narrow the type first: if (error instanceof Error) { error.message; }. This is much safer because you cannot assume what type was thrown — JavaScript allows throwing any value (throw "a string", throw 42, not just Error objects). Forcing unknown prevents you from blindly accessing error.message when the thrown value might not be an Error instance. Explicitly type the variable as unknown in older TypeScript: catch (error: unknown). Best practice: always narrow catch variables before using them — check error instanceof Error and handle both cases.
Common Mistake
Many candidates answer correctly but can't explain the 'why'. Always be prepared to justify your answer with a concrete example or use case from your TypeScript experience.
Previous
What is strict null checks and why is it important?
Next
What are recursive types in TypeScript?