1

我使用的是内置的解析器从源代码生成的AST:如何从打字稿AST中获取推断的类型?

const ts = require('typescript') 
//... 
const ast = ts.createSourceFile(filename, fs.readFileSync(filename).toString(), ts.ScriptTarget.ES6, true) 

有没有办法让推断出的类型从AST的变量?例如,在下面的代码中,bar的类型为IBar。编译器知道该类型--- bar.foo()不能编译---我如何以编程方式获取类型?

interface IBar { bar() } 
const foo : IBar = //... 
export const bar = foo 

回答

2

编译器知道该类型--- bar.foo()不会编译---我如何通过编程获得类型?

AST不是完整故事类型检查。你需要一个TypeChecker

最简单的解决方案是创建一个程序(一些文档https://basarat.gitbooks.io/typescript/content/docs/compiler/program.html),然后使用program.getTypeChecker(更多文档https://basarat.gitbooks.io/typescript/content/docs/compiler/checker.html

+0

在我的答案中添加了详细信息。小心添加任何东西? –

1

至于我可以告诉这个开了窍:

// load typechecker for file 
const program = ts.createProgram([filename], {}); 
const typeChecker = program.getTypeChecker() 
// now get ast 
const ast = ts.createSourceFile(filename, filecontents, ts.ScriptTarget.ES6, true)) 
// get node under question using ts.forEachChild (not shown here) 
const node = // ... 

const type = typeChecker.getTypeAtLocation(node); 

唯一奇怪的是,在变量声明中,“节点”必须是value(又名FirstLiteralToken),而不是label(又名标识符)---否则,类型是未定义的。 例如,如果文件内容是const foo = 123,将“foo”的节点传递给typeChecker#getTypeAtLocation将不起作用。您必须通过节点“123”

+0

这几乎不能解决问题中提出的问题 –