TypeScript Compiler API – Syntax Parsing

I’ve been working with the TypeScript compiler API to build a custom compiler for my current employer, who effectively wants to abstract strings into resource files automatically. It’s a similar concept to what Android and iOS development environments provide structure for OOB.

For example, given a simple class in an input file:

Abstracting the properties on the class into a structured resource file might be done with regular expressions in such a simple example – but to do it the “right” way you’d end up re-writing the compiler that interprets the TypeScript anyway!

The TypeScript compiler API exposes you to the ability to walk the Abstract Syntax Tree (AST) and identify each type of “node” in the tree. The node types are listed in the SyntaxKind enum.

It’s easy enough to take a TypeScript file as input and output the syntax of every node, and you could build logic on top of this syntax identification.

To use this code, it must be transpiled to javascript before running on node. The entire nodejs/typescript runtime and environment setup is a mess, I find it fickle to deal with compared to the ease of other languages. Note that you need to npm install both typescript and typings.

Your output may look something like this:
tsc  showSyntax.ts console output

This process generates the showSyntax.js in the same folder.

You can run the output showSyntax.js on node, passing one or more filenames as input. Here’s the example helloworld.ts above:

showSyntax of helloworld.ts

I think it is interesting to read the code through the eyes of the compiler, seeing the SyntaxKind description of each node. It’s a useful learning aid.

999 total views, 3 views today

Leave a Reply

Your email address will not be published. Required fields are marked *