Preventing Runtime Errors (with Types)
See how types can surface runtime errors
Preventing 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.
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
Now we have a parser written in TypeScript, but need a way to execute it.
There are a few options, including running babel on
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
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