Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get inferred type from a typescript AST?

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
like image 409
U Avalos Avatar asked Jan 12 '16 05:01

U Avalos


People also ask

Does TypeScript have type inference?

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.

How does TypeScript inference work?

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.

What is TypeScript AST?

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.


1 Answers

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) 🌹

like image 184
basarat Avatar answered Sep 29 '22 07:09

basarat