Skip to content
Tutorials Center
My learning

Topics

Lesson 72 of 96 ยท TypeScript in Practice

Debugging TypeScript

Learn to debug TypeScript with source maps, VS Code launch configurations, node --inspect, tsx and ts-node, breakpoints, logpoints and how to read stack traces and type errors.

Browsers and Node.js cannot run TypeScript directly (Node can strip simple types, but it still runs JavaScript). Your program runs as generated JavaScript, yet the bugs you hunt live in your .ts files. Debugging TypeScript is the art of connecting those two worlds so that breakpoints, stack traces and variables show your original code.

This lesson covers source maps, debugging in VS Code, the node --inspect flag, running TypeScript directly with tsx or Node itself, how to read a stack trace, and the techniques that catch bugs before you ever need a debugger.

The first line of defense: the type checker

Many bugs never reach the debugger, because the compiler finds them. Before you start stepping through code, run the type check and read the errors from the top. Later errors are often caused by the first one:

Terminal
npx tsc --noEmit

--noEmit checks types without writing files. A type error has a code (for example TS2322) that you can search for, and TypeScript 7 gives detailed messages that spell out why two types are not assignable. See Strict Mode for the options that make the checker catch the most.

Source maps connect JavaScript to TypeScript

A source map is a file (main.js.map) that records, for each position in the generated JavaScript, where it came from in the TypeScript source. Debuggers and error reporters read it to show your original lines.

Turn them on in tsconfig.json:

JSON
{
  "compilerOptions": {
    "sourceMap": true,
    "outDir": "dist"
  }
}

The compiler then writes a .js.map file next to every .js file and adds a comment at the bottom of the JavaScript, //# sourceMappingURL=main.js.map. Debuggers follow that comment. Options you may also see:

Option What it does
sourceMap Writes .js.map files next to the output
inlineSourceMap Embeds the map in the .js file itself
inlineSources Also embeds your .ts text, so the map works even without the source files
declarationMap Maps .d.ts files back to .ts (so "Go to definition" opens your source in libraries)

Node does not apply source maps to stack traces unless you ask. The flag is --enable-source-maps, and the runner on this site uses it. Run the program below and look at the line numbers in the stack trace: they point at the TypeScript file, not at generated JavaScript.

TypeScript A stack trace that points at the .ts file

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Read a stack trace from the top: the first line names the error, and the first at line shows where it was thrown. Walk down the following lines to see who called whom. The as Order[] assertion hid the problem from the compiler; the data had no items, so reduce failed at runtime. The lesson to take away: values that cross a boundary (JSON, network, user input) need validation. See Validating Data with Zod.

Debugging in VS Code

VS Code has a built-in debugger for Node.js. The fastest path is the JavaScript Debug Terminal: open it from the terminal drop-down, run your program as usual (node dist/main.js), and every breakpoint you set in your .ts files works, provided source maps are on.

For repeatable setups, add a launch configuration in .vscode/launch.json:

JSON
{
  "version": "0.2.0",
  "configurations": [
    {
      "name": "Debug compiled app",
      "type": "node",
      "request": "launch",
      "program": "${workspaceFolder}/dist/main.js",
      "preLaunchTask": "tsc: build - tsconfig.json",
      "outFiles": ["${workspaceFolder}/dist/**/*.js"],
      "skipFiles": ["<node_internals>/**"]
    },
    {
      "name": "Debug current file with tsx",
      "type": "node",
      "request": "launch",
      "runtimeExecutable": "npx",
      "runtimeArgs": ["tsx"],
      "program": "${file}",
      "console": "integratedTerminal",
      "skipFiles": ["<node_internals>/**"]
    }
  ]
}

The important fields: outFiles tells the debugger where generated JavaScript lives so it can apply source maps, preLaunchTask rebuilds before each run, and skipFiles keeps you out of Node's own code when you step.

Breakpoints that do more than pause

Right-click the gutter next to a line number for three kinds of breakpoint:

  • A conditional breakpoint only pauses when an expression is true, such as order.id === 2. It saves you from stepping through thousands of loop iterations.
  • A logpoint prints a message (with inside braces) without pausing and without changing your code, so there is no stray console.log to remove later.
  • A hit count breakpoint pauses on the nth time the line is reached.

While paused, the Variables panel shows locals, the Watch panel evaluates expressions you type, and the Call Stack lets you jump to callers. The Debug Console evaluates TypeScript-looking expressions, but remember that it runs JavaScript, so type annotations are not allowed there.

node --inspect

Node ships a debugger server. Start your program with --inspect-brk and it waits for a debugger to attach before running the first line:

Terminal
node --inspect-brk --enable-source-maps dist/main.js

Then attach from VS Code ("Attach to Node Process"), or open chrome://inspect in Chrome and click inspect under the Remote Target. Chrome DevTools opens with your TypeScript files in the Sources panel when source maps are present. --inspect (without -brk) starts the server but does not pause, which suits long-running servers you attach to later.

The inspector port gives full control over your process. Never expose --inspect to a public network interface; it binds to 127.0.0.1 by default, and you should keep it that way (use an SSH tunnel for remote machines).

Running TypeScript directly: tsx, ts-node and Node

Compiling before every run slows the loop. Three tools remove that step:

  • Node.js itself (22.18 and newer, plus all of 24) runs .ts files by stripping the types: node main.ts. It only handles erasable syntax, and it does not type check.
  • tsx (npx tsx main.ts) transpiles on the fly with esbuild, supports everything including enums, and has a watch mode: npx tsx watch main.ts. It does not type check either.
  • ts-node type checks while running (slower), unless you pass --transpile-only.

All three generate source maps in memory, so stack traces and breakpoints point at the .ts file. To debug with tsx, use node --inspect-brk --import tsx main.ts (or the launch configuration above). Because none of the fast runners type check, keep tsc --noEmit in your scripts and in CI.

Debugging without a debugger

A debugger is not always available, or needed. Some quick tools:

TypeScript Better console output

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with node:readline or readFileSync(0)), it gets the next line from this box.

Use labels so output tells you what it is: console.log('user:', user) beats console.log(user). console.table is perfect for arrays of records, and console.assert only prints when the condition is false.

A powerful trick for types is to ask the compiler what it sees. Hover over a variable in your editor to see its inferred type, or force an error to display it:

TypeScript
const result = [1, 2, 3].map((n) => String(n));
const probe: { __show: never } = result;
// error TS2741: Property '__show' is missing in type 'string[]' but required in type '{ __show: never; }'.

That reveals the type (string[]) in the message. Remove the line once you know.

Common debugging situations

"It works in tsc but fails at runtime." A type assertion (as), a non-null assertion (!), an any, or untrusted data is hiding the problem. Search for those first. A good search: grep -rn " as \| any\b\|!\." src.

"Breakpoints turn gray ('unbound')." The debugger could not find a source map. Check sourceMap: true, check that outFiles matches the output folder, and confirm the .js file ends with a sourceMappingURL comment.

"Stack trace shows dist/main.js:42." Source maps are off or Node was not started with --enable-source-maps. In production, many teams upload source maps to an error tracker (such as Sentry) instead of shipping them publicly.

"The line numbers are off by a few." The output file is older than the source. Rebuild, or run in watch mode: tsc --watch.

"Type error is huge and unreadable." Fix the first error only, then recompile. Break complex types into named aliases so messages show names instead of expanded structures.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. What does a source map do?

    Debuggers and error reporters use it to show original .ts lines, variables and stack frames.
  2. 2. Which Node flag makes stack traces show TypeScript line numbers when the code was compiled with sourceMap: true?

    Node only applies source maps to error stack traces when --enable-source-maps is passed.
  3. 3. What does a logpoint do in VS Code?

    Logpoints are breakpoints that log. They are not part of your source, so nothing needs cleaning up.
  4. 4. Why should you keep running tsc --noEmit even if you run code with tsx?

    Fast runners strip or transpile types without checking them, so type errors would go unnoticed.
  5. 5. A value from JSON.parse(...) as Order[] crashes later with "Cannot read properties of undefined". What is the most likely cause?

    Assertions are never checked at runtime. Validate external data instead of asserting its type.

Summary

  • Run tsc --noEmit first, and fix type errors from the top; many bugs never need a debugger.
  • Enable sourceMap so debuggers and stack traces show your .ts files; Node needs --enable-source-maps for traces.
  • In VS Code use the JavaScript Debug Terminal or a launch.json with outFiles, and use conditional breakpoints and logpoints.
  • node --inspect-brk waits for a debugger to attach; never expose the inspector publicly.
  • tsx, ts-node --transpile-only and Node's type stripping run TypeScript directly, but do not type check.
  • Search for as, ! and any when the types say yes but the runtime says no.

Next: Best Practices