How to Extract AST of given Typescript code using the open source Typescript compiler code? How to Extract AST of given Typescript code using the open source Typescript compiler code? typescript typescript

How to Extract AST of given Typescript code using the open source Typescript compiler code?


Basic code:

const fileNames = ["C:\\MyFile.ts"];const compilerOptions: ts.CompilerOptions = {    // compiler options go here if any...    // look at ts.CompilerOptions to see what's available};const program = ts.createProgram(fileNames, compilerOptions);const typeChecker = program.getTypeChecker();const sourceFiles = program.getSourceFiles();sourceFiles.filter(f => /MyFile\.ts$/.test(f.fileName)).forEach(sourceFile => {    ts.forEachChild(sourceFile, node => {        const declaration = node as ts.Declaration;        if (declaration.name) {            console.log(declaration.name.getText());        }    });});

So if you provided that with a C:\MyFile.ts like:

class MyClass {}interface MyInterface {}

It would output MyClass and MyInterface.

Figuring out everything beyond what I've just shown is a lot of work. It might be more beneficial for you to look at and/or help contribute to this work in progress.


TypeScript compiler doesn't support it but you can do it using recast and babylon@next. Although you will have to trust in the syntax defined by these technologies for representing TypeScript code AST and that they will keep up to date - since TypeScript has new language features release by release (short period of time) - is not like other languages (JavaScript) where you have well defined versions and released in a standard - so if your users start using new language features these technologies (mostly babylon) should keep up to date:

// npm install recast babylon@nextconst source = `interface I {  color: string}class C implements I{  color: string='blue'}`const recast = require('recast')const tsParser = require("recast/parsers/typescript")const ast = recast.parse(source, {  parser: tsParser});console.log(`CODE: ${source}AST: ${JSON.stringify(ast)}`);