Comparing TypeScript Error Handling Techniques: Try-Catch vs Result Types
Learn about two popular error handling techniques in TypeScript—try-catch blocks and Result types—to write safer, clearer code.
Error handling is an important part of writing reliable code in any programming language, including TypeScript. Two common ways to handle errors are using try-catch blocks and using Result types. In this article, we'll compare these approaches so beginners can understand their pros and cons.
### Try-Catch Blocks Try-catch is a traditional method to handle runtime errors. You wrap code that might throw an error inside a try block, and catch the error in the catch block. This allows you to respond to unexpected issues gracefully.
function parseJson(jsonString: string) {
try {
return JSON.parse(jsonString);
} catch (error) {
console.error("Invalid JSON:", error);
return null;
}
}
const data = parseJson('{ "name": "Alice" }');
console.log(data);Try-catch is straightforward and works well for handling errors that throw exceptions. However, it can sometimes make it harder to anticipate all possible error states, and mixing error handling with main logic can reduce readability.
### Result Types Result types are a functional programming pattern to explicitly represent success or failure as part of a function's return type. A Result type typically has two variants: Ok (success) and Err (error). This makes error handling explicit and forces developers to handle both cases.
type Result<T, E> =
| { type: "ok"; value: T }
| { type: "err"; error: E };
function parseJsonResult(jsonString: string): Result<any, string> {
try {
const parsed = JSON.parse(jsonString);
return { type: "ok", value: parsed };
} catch {
return { type: "err", error: "Invalid JSON" };
}
}
const result = parseJsonResult('{ "name": "Alice" }');
if (result.type === "ok") {
console.log("Parsed data:", result.value);
} else {
console.error("Error:", result.error);
}Using Result types improves code clarity because it clearly separates successful and failed outcomes. It encourages handling errors explicitly instead of relying on exceptions. However, it requires more verbose code and understanding of union types.
### When to Use Which? - Use try-catch for simple cases where exceptions are expected and can be handled locally. - Use Result types when you want to enforce explicit handling of errors and make success/failure part of your function contract. Both methods have their place in TypeScript development. Combining them smartly can help create robust and maintainable applications.
By understanding these two techniques, beginners can write safer, clearer error handling code in TypeScript that matches their project needs.