Mastering TypeScript's Type Narrowing for Advanced Error Handling
Learn how to use TypeScript's type narrowing features to write safer and more precise error handling code, perfect for beginners looking to improve their TypeScript skills.
TypeScript's powerful type system helps catch errors at compile time, but sometimes you also need to handle errors at runtime. Type narrowing is a technique that lets TypeScript understand the exact type of a variable in a specific part of your code, making error handling more precise and reliable.
In JavaScript, errors are often handled with try-catch blocks where the caught error is typed as 'any' by default, losing valuable type information. TypeScript allows us to narrow down the type of an unknown error, enabling safer access to its properties and better control over the error flow.
Let's dive into an example:
function handleError(e: unknown) {
if (e instanceof Error) {
// TypeScript now knows e is an Error object
console.error('Error message:', e.message);
} else if (typeof e === 'string') {
// We narrowed e to string
console.error('String error:', e);
} else {
console.error('Unknown error:', e);
}
}
try {
throw new Error('Something went wrong!');
} catch (err) {
handleError(err);
}In this code, the function `handleError` accepts an `unknown` type parameter. Using type narrowing inside the function lets TypeScript understand the exact type of the error and safely access the `message` property if applicable.
You can also create custom type guard functions to improve reusability and clarity:
function isError(e: unknown): e is Error {
return e instanceof Error;
}
function handleError(e: unknown) {
if (isError(e)) {
console.error('Caught an error:', e.message);
} else {
console.error('Non-error thrown:', e);
}
}By mastering type narrowing with `instanceof`, `typeof`, and custom type guards, you can create advanced and dependable error handling logic in your TypeScript projects that will reduce bugs and improve maintainability.