How to handle exceptions in TypeScript with type safety?
Instruction: Discuss strategies for writing exception handling code in TypeScript that maintains type safety.
Context: This question tests the candidate's ability to implement robust error handling mechanisms in TypeScript, ensuring exceptions are managed in a type-safe manner.
Updated
Official answer available
Read the opening below, then unlock the full answer and practical guidance.
JavaScript can throw any value, including a string, null or an Error. Treat a caught value as unknown until runtime checks establish what can be used. useUnknownInCatchVariables enables that default; an explicit catch (error: unknown) also makes the boundary clear.
class ValidationError extends Error { constructor(message: string) { super(message); this.name = "ValidationError"; } } function describeFailure(error: unknown): string { if (error instanceof ValidationError) return "Invalid input"; if (error instanceof Error)...