使用 TypeScript API 查找类型引用

lil*_*zek 3 abstract-syntax-tree typescript

我试图找到 a 的种类(类、接口、类型别名、枚举...)TypeReference

我有这个:

const anode = node as ts.TypeReferenceNode;
const symbol = this.typechecker.getSymbolAtLocation(anode.typeName) as ts.Symbol;
const type = this.typechecker.getTypeOfSymbolAtLocation(symbol, anode);
const decls = symbol.getDeclarations() as ts.Declaration[]; 
Run Code Online (Sandbox Code Playgroud)

但是调用getSymbolAtLocation返回undefined

anodeTypeReferenceNode根据 VSC 调试器是一个(种类 159):

在此处输入图片说明

ETypes对枚举引用的转义文本引用。

lil*_*zek 5

我找到了一个解决方案:

const anode = node as ts.TypeReferenceNode;
const type = this.typechecker.getTypeAtLocation(anode);
const symbol = type.symbol || type.aliasSymbol;
const decls = symbol.getDeclarations() as ts.Declaration[];
Run Code Online (Sandbox Code Playgroud)

decls数组中您可以找出声明是否为接口、类等...