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:

1

2

3

4

5

6

7

8

9

10

11

classGreeter{

id=101;

greeting="Hello World!";

greet(){

console.log(this.greeting);

}

};

let greetMe=newGreeter();

greetMe.greet();

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.

1

tsc showSyntax.ts

Your output may look something like this:

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:

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.