This video is available to students only

Add Type Safety and Prevent Runtime Errors With AST

See how types can surface runtime errors

In the previous lesson, the initial script for logging the numeric values worked for one specific code snippet (2 + (4 * 10)). Updating that to another code snippet ((2 + 4) * 10) resulted in a runtime error, because the underlying AST changed.

Ideally, this issue could have been caught before the script was even run.

Adding type-safety#

Fortunately, many of these issues can be caught in your editor, or at compile-time, with TypeScript. The type definitions define all of the nodes and each node's specific properties. This means only valid properties can be accessed. Additionally, since many properties can be polymorphic, or point to many other nodes, it requires "narrowing" the type to only the node(s) with that property defined. This results in many more checks and an overall more robust script leading to fewer runtime errors.

You can think of the AST that the type definitions represent as the most "generic" AST, since it represents every possible node and property.

TypeScript is not a requirement, but it helps avoid runtime errors and provides code completion, which makes it easier to work with complex nodes.

To start, rename the previous parser.js file to parser.ts and convert the require to an import.

Now we have a parser written in TypeScript, but need a way to execute it.

There are a few options, including running babel on parser.ts and transpiling it to JavaScript. 😅

A simpler approach is to execute the script with ts-node. This package can be used in the same way as node, but with TypeScript support.

All set! ✨ The script can now be run with ts-node.

Note that npx (not npm) was used to execute the ts-node binary. This will be used throughout the rest of the course.

Running the script should produce the following output.

The script isn't executed because there are type errors. The @babel/parser package includes its own TypeScript type definitions, which is why nothing new was installed, but we're now seeing type errors. If you open this file in an editor with TypeScript support (such as VSCode) these type errors will also show up in the editor.

Fixing the type errors#

The type errors are all along the same lines with the message:

What is type Statement?

This lesson preview is part of the Practical Abstract Syntax Trees course and can be unlocked immediately with a \newline Pro subscription or a single-time purchase. Already have access to this course? Log in here.

Unlock This Course

Get unlimited access to Practical Abstract Syntax Trees, plus 70+ \newline books, guides and courses with the \newline Pro subscription.

Thumbnail for the \newline course Practical Abstract Syntax Trees