typescript - 使用 TypeScript API 查找类型引用

标签 typescript abstract-syntax-tree

我正在尝试查找 TypeReference 的种类(类、接口(interface)、类型别名、枚举...)。

我有这个:

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[]; 

但是对 getSymbolAtLocation 的调用返回 undefined

根据 VSC 调试器,

anode 是一个 TypeReferenceNode(种类 159):

enter image description here

并且 escapedText ETypes 对枚举引用的引用。

最佳答案

我找到了一个解决方案:

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[];

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

关于typescript - 使用 TypeScript API 查找类型引用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45660003/

相关文章:

javascript - Match a URL with placeholders 与 URL with filled placeholders

haskell - 在存在递归绑定(bind)器的情况下,将 PHOAS 变量的正负事件分开

c# - Lambda 表达式 Compile() 方法有什么作用?

javascript - 无法使用 Esprima/Acorn : unexpected token '(' 解析函数

javascript - 如何使用 TypeScript 停止 d3 中的事件传播?

javascript - typescript 中的 'd3 和 'd3-hexbin' 作为全局库

typescript - 如何获取应用程序使用 typescript 运行的路径?

TypeScript 问题 - TypeError : Cannot read property 'watchRun' of undefined

python - 带有元组字符串表示的格式错误的字符串 ValueError ast.literal_eval()

解析函数中某些表达式的 Python 装饰器