如何知道TypeScript编译器中的符号声明类型?

时间:2017-06-07 19:58:30

标签: typescript typescript-compiler-api

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

现在,以下应用可以打印出pPersonagewalk

但是如何知道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;

// user-app.ts

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

1 个答案:

答案 0 :(得分:1)

检查符号上的标记。

即:

if(symbol.flags & ts.SymbolFlags.Class) {
   // this symbol is a class 
} else if (symbol.flags & ts.SymbolFlags.Interface) {
   // this is an interface 
}
相关问题