2017-06-07 52 views
0

我正試圖建立一個代碼分析工具,遵循Compiler API如何知道TypeScript編譯器中符號的類型?

現在下面的應用程序可以打印出p,Person,age, walk

但是如何知道Person是接口,walk是函數等?由於

// app.ts

import * as ts from 'typescript'; 

const userAppFile = './user-app.ts'; 
const apiFile = './api.d.ts'; 

const program = ts.createProgram([userAppFile, apiFile], ts.getDefaultCompilerOptions()); 
const checker = program.getTypeChecker(); 
const sourceFile = program.getSourceFile(userAppFile); 

function printApi(node) { 
    const symbol = checker.getSymbolAtLocation(node); 

    if (symbol) console.log(symbol.name); 

    ts.forEachChild(node, printApi); 
} 

printApi(sourceFile); 

// api.d.ts

interface Person { 
    age: number; 
} 

declare function walk(speed: number): void; 

//用戶app.ts

const p: Person = { age: 10 }; 
walk(3); 

回答

1

你檢查一下e符號上的標誌。

即:

if(symbol.flags & ts.SymbolFlags.Class) { 
    // this symbol is a class 
} else if (symbol.flags & ts.SymbolFlags.Interface) { 
    // this is an interface 
} 
+0

謝謝,工作完美! –

相關問題