Debugging: TypeScript

Catching Errors at Compile Time

TypeScript is a bit easier to debug than Javascript because it is compiled to Javascript, and many errors are caught at compile time. The name of the command-line compiler is tsc.

Consider this buggy typescript file named test.ts:

function errorProne(a: number, b: string) {
console.log(a);
console.log(b);
}

errorProne("hi");

Notice that when we call the function errorProne, we don’t provide the correct parameters. Let’s compile this little script to Javascript at the command line.

> tsc test.ts
test.ts(6,1): error TS2346: Supplied parameters do not match any signature of call target.

TypeScript has identified your error before you even ran the script.

Catching Errors in the Browser

The TypeScript compiler doesn’t catch all errors, though. Sometimes you can only catch them in the browser. Let’s assume you’ve got an html webpage like this (index.html) that does nothing but run a compiled TypeScript (i.e., a Javascript) file:

<html>
    <head>
        <script src="test.js"></script>
    </head>
    <body>
    </body>
</html>

To debug this script, use the Firefox web browser with the Firebug extension installed. This useful addon is a great tool for web development.

Be sure firebug is set to show stack traces. Type about:config into Firefox and make sure extensions.firebug.showStackTrace is set to true.

To debug a website, go to that website and enable Firebug by clicking on the appropriate icon in the tool bar.

A console will pop up at the bottom of the window.

You may need to enable the different tabs individually. Once you’ve done that, reload the page, and Firebug will analyze it for you. To demonstrate, let’s consider this buggy code:

function func1(a) {
    func2(a);
}

function func2(b) {
    console.log(b.length);
}

func1(undefined);

Here, we pass the undefined variable to func1, which then passes that same variable to func2, which then tries to determine the length. But an undefined variable has no length, so an error is produced.

Here’s the output in Firebug:

Click on the little arrow to the left of the error message and you can see the exact path the code took to get to that error. This path is called the stack trace:

You can also click on the blue-highlighted text to go to that line in the code. Makes debugging much easier.