TypeScript Debugging Techniques

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.

Basic Debugging Techniques

Console Logging

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);

				
			

Explanation:

  • console.log('add result:', result); outputs the value of result to the console.
  • Running this code will show add result: 5 in the console.

Output:

				
					add result: 5

				
			

Using Debugger Statement

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);

				
			

Explanation:

  • When the debugger statement is encountered, execution will pause, allowing you to inspect variables and the call stack.

IDE Debugging Tools

Visual Studio Code (VS Code)

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": ["<node_internals>/**"],
      "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);

				
			

Explanation:

  • Set breakpoints in index.ts to pause and inspect variables during execution.

Output:

				
					divide result: 2

				
			

WebStorm

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.

Browser Developer Tools

Using Chrome DevTools

Chrome DevTools is a powerful suite of web development tools built directly into the Google Chrome browser.

  • Source Maps: Ensure that source maps are enabled in your TypeScript configuration (tsconfig.json):
				
					{
  "compilerOptions": {
    "sourceMap": true
  }
}

				
			
  • Inspecting Code: Open DevTools (F12 or Ctrl+Shift+I), go to the “Sources” tab, and you should see your original TypeScript files if source maps are configured correctly.
  • Setting Breakpoints: Set breakpoints in your TypeScript code, and refresh the page to pause execution at those points.
				
					// src/app.ts
function greet(name: string): string {
  return `Hello, ${name}!`;
}

console.log(greet('World'));

				
			

Explanation:

  • Open app.ts in Chrome DevTools, set a breakpoint, and inspect the variables.

Output:

				
					Hello, World!

				
			

Firefox Developer Tools

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.

Advanced Debugging Techniques

Using Linting Tools

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

				
			

Explanation:

  • ESLint checks your TypeScript code for syntax errors, potential bugs, and adherence to coding standards.

Profiling and Performance Analysis

Use tools like the Chrome DevTools Performance panel to analyze and improve the performance of your TypeScript applications.

  • Recording Performance: Open DevTools, go to the “Performance” tab, start recording, interact with your application, and stop recording to analyze the results.
				
					// 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');

				
			

Explanation:

  • Use console.time and console.timeEnd to measure the execution time of heavyComputation.

Output:

				
					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 !❤️

Table of Contents

Contact here

Copyright © 2025 Diginode

Made with ❤️ in India