Menu Close

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:

class Greeter {
    id = 101;
    greeting = "Hello World!";
    greet() {
        console.log( this.greeting );

let greetMe = new Greeter();


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.

/// <reference path="typings/node/node.d.ts" />

import {readFileSync} from "fs";
import * as ts from "typescript";

export function showSyntax(sourceFile: ts.SourceFile) {
    function showNodeSyntax(node: ts.Node) {
        console.log(node.kind + " : " + ts.SyntaxKind[node.kind] + " : " + node.getText());
        ts.forEachChild(node, showNodeSyntax);

const fileNames = process.argv.slice(2);
fileNames.forEach(fileName => {
    let sourceFile = ts.createSourceFile(fileName, readFileSync(fileName).toString(), ts.ScriptTarget.ES6, true);

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.

tsc showSyntax.ts

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.

 5,165 total views,  2 views today

Leave a Reply

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