Debugging is a crucial part of the software development process. TypeScript, with its static typing and enhanced tooling support, helps reduce the number of bugs, but debugging is still essential. This chapter will guide you through various debugging techniques in TypeScript, from basic methods to advanced strategies. We will cover how to use console logging, integrated development environment (IDE) tools, browser developer tools, and more.
The most straightforward debugging technique is using console.log()
to output values to the console.
function add(a: number, b: number): number {
const result = a + b;
console.log('add result:', result);
return result;
}
add(2, 3);
console.log('add result:', result);
outputs the value of result
to the console.add result: 5
in the console.
add result: 5
The debugger
statement can be placed in your code to pause execution and inspect variables.
function multiply(a: number, b: number): number {
const result = a * b;
debugger;
return result;
}
multiply(2, 3);
VS Code offers robust debugging support for TypeScript.
Setting Up Debug Configuration: Create a .vscode/launch.json
file:
{
"version": "0.2.0",
"configurations": [
{
"type": "node",
"request": "launch",
"name": "Launch Program",
"skipFiles": ["/**"],
"program": "${workspaceFolder}/src/index.ts",
"outFiles": ["${workspaceFolder}/dist/**/*.js"]
}
]
}
Setting Breakpoints: Click in the gutter next to the line number to set a breakpoint.
Starting the Debugger: Press F5
to start debugging. The debugger will pause at the breakpoints, allowing you to inspect variables, the call stack, and evaluate expressions.
// src/index.ts
function divide(a: number, b: number): number {
if (b === 0) {
throw new Error('Division by zero');
}
return a / b;
}
const result = divide(6, 3);
console.log('divide result:', result);
index.ts
to pause and inspect variables during execution.
divide result: 2
JetBrains WebStorm also provides powerful debugging tools for TypeScript.
Setting Up Debug Configuration: Go to Run > Edit Configurations
, add a new Node.js configuration, and set the main file to your TypeScript entry point.
Setting Breakpoints and Starting the Debugger: Similar to VS Code, set breakpoints and start the debugger to pause execution and inspect your code.
Chrome DevTools is a powerful suite of web development tools built directly into the Google Chrome browser.
tsconfig.json
):
{
"compilerOptions": {
"sourceMap": true
}
}
F12
or Ctrl+Shift+I
), go to the “Sources” tab, and you should see your original TypeScript files if source maps are configured correctly.
// src/app.ts
function greet(name: string): string {
return `Hello, ${name}!`;
}
console.log(greet('World'));
app.ts
in Chrome DevTools, set a breakpoint, and inspect the variables.
Hello, World!
Firefox Developer Tools also support TypeScript debugging with source maps.
Inspecting Code: Open Developer Tools (F12
), go to the “Debugger” tab, and you should see your TypeScript files if source maps are enabled.
Setting Breakpoints: Similar to Chrome, set breakpoints and refresh the page to debug your TypeScript code.
Linting tools like ESLint can catch potential errors and enforce coding standards before you run your code.
Setting Up ESLint: Install ESLint and the TypeScript plugin:
npm install eslint @typescript-eslint/parser @typescript-eslint/eslint-plugin --save-dev
Create an .eslintrc.json
configuration file:
{
"parser": "@typescript-eslint/parser",
"plugins": ["@typescript-eslint"],
"extends": [
"eslint:recommended",
"plugin:@typescript-eslint/recommended"
],
"rules": {
"no-unused-vars": "error",
"no-console": "warn"
}
}
Running ESLint: Add a lint script to your package.json
:
"scripts": {
"lint": "eslint 'src/**/*.{ts,tsx}'"
}
Run the linter:
npm run lint
Use tools like the Chrome DevTools Performance panel to analyze and improve the performance of your TypeScript applications.
// Performance Example
function heavyComputation(num: number): number {
let result = 0;
for (let i = 0; i < num; i++) {
result += i;
}
return result;
}
console.time('heavyComputation');
console.log(heavyComputation(1e6));
console.timeEnd('heavyComputation');
console.time
and console.timeEnd
to measure the execution time of heavyComputation
.
heavyComputation: 15.123ms
Debugging TypeScript efficiently requires a combination of basic and advanced techniques. From simple console.log statements to sophisticated IDE tools, browser developer tools, and linting and testing frameworks, mastering these techniques ensures you can quickly identify and resolve issues in your code. Happy coding !❤️