Reputation: 49814
I am trying to build a code analysis tool following the Compiler API.
Right now the app below can print out p
, Person
, age
, walk
.
But how to know Person
is interface, walk
is function, etc.? Thanks
// 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);
Upvotes: 1
Views: 1307
Reputation: 794
You check the flags on the symbol.
I.e.:
if(symbol.flags & ts.SymbolFlags.Class) {
// this symbol is a class
} else if (symbol.flags & ts.SymbolFlags.Interface) {
// this is an interface
}
Upvotes: 1