Traversing the TypeScript AST

We have learned how to visualize the TypeScript AST using the TypeScript AST viewer online. At this point, it is normal to ask ourselves where all this information is coming from. In this section, we are going to demonstrate how to use the TypeScript compiler APIs to access the AST.

After creating a package.json file and installing TypeScript using npm, the first thing that we need to do is to create a new TypeScript file and import TypeScript as a module:

import * as ts from "typescript"; 

Then we need to declare the configuration of the TypeScript compiler using an object literal:

const options = { 
    module: ts.ModuleKind.CommonJS, 
    target: ts.ScriptTarget.ES5, 
}; 

Next, we need to create a new program:

const ...

Get Learning TypeScript 2.x - Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.