TypeScript Error Handling
Error handling in TypeScript uses the same try/catch/finally structure as JavaScript, but you need to be careful with types since caught errors are typed as `unknown` by default in strict mode.
Because the type of a caught error isn't guaranteed to be an `Error` object, it's good practice to check its type before accessing properties like `.message`, keeping your error handling both safe and informative.
try {
// risky code
} catch (error: unknown) {
if (error instanceof Error) {
console.log(error.message);
}
}try/catch with types
Inside a catch block, the caught value has type `unknown` under strict settings, so you should narrow it (for example with `instanceof Error`) before using error-specific properties.
Custom error classes
You can create custom error types by extending the built-in Error class, adding extra properties or a distinct name to represent specific kinds of failures in your application.
try {
throw new Error("Something went wrong");
} catch (error: unknown) {
if (error instanceof Error) {
console.log(error.message);
}
}Something went wronginstanceof Error narrows the unknown caught value so .message can be accessed safely.
class ValidationError extends Error {
constructor(message: string) {
super(message);
this.name = "ValidationError";
}
}
try {
throw new ValidationError("Invalid input");
} catch (error: unknown) {
if (error instanceof ValidationError) {
console.log(`${error.name}: ${error.message}`);
}
}ValidationError: Invalid inputA custom error class lets you distinguish specific error types with instanceof checks.
Key points
- Caught errors are typed as unknown under strict settings.
- Use instanceof Error to safely narrow a caught error before accessing its properties.
- Custom error classes can extend the built-in Error class.
- Good error handling keeps both runtime safety and type safety.
