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
Adding type annotations to our code is extra code we need to write, which consumes a little more of our time and bloats our code. TypeScript has something called type inference, which means, in many cases, it can work out a variable's type without it having a type annotation.
TypeScript infers types of variables when there is no explicit information available in the form of type annotations. Types are inferred by TypeScript compiler when: Variables are initialized. Default values are set for parameters.
The AST is a data structure to represent the structure of your source file in a format readable by machines. Indeed, if I throw the above example in the TypeScript AST Viewer I get immediate access to the AST.
The compiler knows about that type---bar.foo() doesn't compile---how can I programmatically get the type?
The AST
is not the complete story for TypeChecking. You need a TypeChecker
.
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) 🌹
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With