0

我正在尝试按照Compiler API构建代码分析工具。

现在下面的应用程序可以打印出p, Person, age, walk.

但是如何知道Person是接口,walk是功能等呢?谢谢

// 应用程序.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;

// 用户应用程序.ts

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

1 回答 1

1

您检查符号上的标志。

IE:

if(symbol.flags & ts.SymbolFlags.Class) {
   // this symbol is a class 
} else if (symbol.flags & ts.SymbolFlags.Interface) {
   // this is an interface 
}
于 2017-06-07T21:14:23.453 回答