I'm using the built-in parser to generate the AST from source code:
const ts = require('typescript')
//...
const ast = ts.createSourceFile(filename, fs.readFileSync(filename).toString(), ts.ScriptTarget.ES6, true)
Is there a way to get the inferred type of a variable from the AST? For example, in the code below, bar is of type IBar. The compiler knows about that type---bar.foo() doesn't compile---how can I programmatically get the type?
interface IBar { bar() }
const foo : IBar = //...
export const bar = foo
The
ASTis not the complete story for TypeChecking. You need aTypeChecker.The simplest solution is to create a program (some docs https://basarat.gitbooks.io/typescript/content/docs/compiler/program.html) and then use
program.getTypeChecker(more docs https://basarat.gitbooks.io/typescript/content/docs/compiler/checker.html)