如何通过TypeScript原生编译器API获取Map的推断类型?
使用TypeScript 5.0.4原生编译器API获取推断类型
你当前通过文件符号获取变量类型的方式存在问题,正确的思路是直接定位到map变量对应的AST节点,再通过类型检查器获取其推断类型,步骤如下:
遍历AST找到目标变量节点
递归遍历源文件的AST结构,定位到export const map对应的VariableDeclaration节点:function findMapVariable(node: ts.Node): ts.VariableDeclaration | undefined { if (ts.isVariableDeclaration(node) && node.name.getText() === 'map') { return node; } for (const child of node.getChildren()) { const result = findMapVariable(child); if (result) return result; } return undefined; } const mapVarNode = findMapVariable(fileNode)!;通过类型检查器获取推断类型
拿到变量节点后,直接调用类型检查器的getTypeAtLocation方法获取其推断类型:const mapType = checker.getTypeAtLocation(mapVarNode);转换为可读的类型字符串
用typeToString方法将类型对象转换为直观的字符串格式:console.log(checker.typeToString(mapType)); // 输出 "Map<number, string>"
原方法失效的原因
你之前通过fileSymbol和fileType.getProperty获取的是模块导出的符号,但直接对该符号调用getTypeOfSymbol无法正确解析推断类型——变量的推断类型是绑定到其初始化表达式的AST节点上的,而非模块符号的属性类型。
另外,NewExpression.typeArguments返回undefined是正常现象,因为这里的类型是TypeScript自动推断生成的,并没有显式写在代码中,必须通过类型检查器计算才能得到正确的推断结果。
内容的提问来源于stack exchange,提问作者Michael Jonker
相关产品推荐
相关产品推荐

