2

I want to parse TypeScript projects into ASTs.

I can parse single file by :

import ts = require("typescript");
var fs          = require('fs');
var util      = require('util');


const ast = ts.createSourceFile('sample.ts', fs.readFileSync('sample.ts').toString(), ts.ScriptTarget.ES6, true);

console.log("AST:"+util.inspect(ast));

I can even loop through the files and filter files by extension and run above code to generate ASt.

However I want to parse the whole project in such a way that the relationships (like imports) will be preserved in AST.

For example:

If, a.ts is referencing var x from b.ts as below:

a.ts:

var y = x;

b.ts:

var x = 5;

In this case signature of x in a .ts should be resolved as : b.ts.x or equivalent.

I just want all such relationships resolved in the ASts as I parse the .ts files one by one.

1 Answer 1

1

You can load your project using

ts.createProgram(rootNames: string[], options: CompilerOptions, host?: CompilerHost, oldProgram?: Program)

rootNames is the list of all typescript files in your project. As far as I know, unless you declare type explicitly, AST will have no reference to it.

for eg. If you have

class MyClass { 
   // some code
}

let instance1 = new MyClass();
let instance2: MyClass = new MyClass();

In AST, node for instance1 will have type property as undefined, for instance2 type property will have proper TypeReference

For type checking you can use Program.getTypeChecker(). This returns a TypeChecker which can be used to analyse files in the program.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.