Day 12: Error Handling and Debugging in TypeScript
I am a MERN stack developer. Here to learn and share my knowledge to help other to grow.
Introduction
On Day 12, we’ll focus on error handling and debugging in TypeScript. Proper error handling and debugging techniques are essential for writing robust and maintainable code. TypeScript provides several tools and practices to help you manage errors and debug your code effectively.
1. Error Handling in TypeScript
Error handling in TypeScript involves dealing with exceptions and runtime errors in a type-safe manner.
1.1. Using try...catch for Error Handling
TypeScript’s try...catch statement is used to handle exceptions that may occur during code execution.
Example:
function divide(a: number, b: number): number {
try {
if (b === 0) {
throw new Error("Cannot divide by zero");
}
return a / b;
} catch (error) {
console.error(error.message);
return NaN; // Return NaN to indicate an error
}
}
const result = divide(10, 0);
console.log(result);
In this example, the divide function handles division by zero by throwing and catching an error.
1.2. Custom Error Types
You can create custom error types in TypeScript to provide more meaningful error information.
Example:
class CustomError extends Error {
constructor(message: string) {
super(message);
this.name = "CustomError";
}
}
function riskyOperation() {
throw new CustomError("Something went wrong!");
}
try {
riskyOperation();
} catch (error) {
if (error instanceof CustomError) {
console.error(error.message);
} else {
console.error("An unexpected error occurred");
}
}
2. Debugging TypeScript Code
Debugging is a critical part of development. TypeScript offers various tools and techniques for debugging code.
2.1. Using Source Maps
Source maps allow you to debug TypeScript code directly in the browser, mapping the compiled JavaScript back to the original TypeScript source.
Setup:
Ensure source maps are enabled in your
tsconfig.json:{ "compilerOptions": { "sourceMap": true } }Run your project, and open the browser’s developer tools to set breakpoints in the TypeScript files.
2.2. Debugging with VSCode
Visual Studio Code (VSCode) provides integrated debugging support for TypeScript.
Setup:
Install the Debugger for Chrome extension in VSCode.
Create a
.vscode/launch.jsonfile with the following configuration:{ "version": "0.2.0", "configurations": [ { "type": "chrome", "request": "launch", "name": "Debug with Chrome", "url": "http://localhost:3000", "webRoot": "${workspaceFolder}/src", "sourceMapPathOverrides": { "webpack:///./src/*": "${workspaceFolder}/*" } } ] }Start debugging by placing breakpoints in your TypeScript code and launching the debug session in VSCode.
3. Common Debugging Techniques
3.1. Using console.log
Although not the most sophisticated method, console.log is a simple way to inspect values and track code execution.
Example:
function add(a: number, b: number): number {
console.log(`Adding ${a} and ${b}`);
return a + b;
}
const sum = add(5, 7);
console.log(`Sum: ${sum}`);
3.2. Type Guards
Type guards are a way to ensure that a variable conforms to a certain type, helping to avoid runtime errors.
Example:
function isString(value: any): value is string {
return typeof value === "string";
}
const someValue: any = "Hello, world!";
if (isString(someValue)) {
console.log(someValue.toUpperCase());
} else {
console.log("Value is not a string");
}
4. Practical Exercises
4.1. Error Handling Practice
Create a new file named
errorHandling.ts.Implement a function that simulates a network request and handles potential errors.
Example Solution:
function fetchData(url: string): Promise<string> {
return new Promise((resolve, reject) => {
setTimeout(() => {
if (url === "") {
reject(new Error("Invalid URL"));
} else {
resolve("Data fetched successfully");
}
}, 1000);
});
}
fetchData("")
.then(data => console.log(data))
.catch(error => console.error(error.message));
4.2. Debugging Practice
Create a new file named
debugging.ts.Write a function with intentional errors and debug it using
console.logand breakpoints.
Example Solution:
function multiply(a: number, b: number): number {
console.log(`Multiplying ${a} and ${b}`);
return a * b;
}
const result = multiply(3, "5"); // Intentional error: string instead of number
console.log(`Result: ${result}`);
5. Conclusion
Today, we covered error handling and debugging techniques in TypeScript. You learned how to handle exceptions, create custom error types, and utilize tools like source maps and VSCode for effective debugging. Mastering these techniques will help you build more reliable and maintainable TypeScript applications.

