如何通过TypeScript Compiler API获取函数的推断返回类型?
获取TypeScript函数的推断返回类型(Compiler API实现)
当然可以获取函数的推断返回类型,但你之前用的transpileModule仅负责代码转译,不会执行完整的类型分析流程。要提取类型信息,需要基于TypeScript Compiler API创建完整的程序实例,借助类型检查器来实现。
实现代码示例
import * as ts from "typescript"; // 目标源代码 const sourceCode = "function foo(xs: Array<number>) { let total=0; for (const x of xs) { total += x; } return total; }"; const fileName = "virtual.ts"; // 创建内存源文件 const sourceFile = ts.createSourceFile( fileName, sourceCode, ts.ScriptTarget.Latest, true ); // 配置编译选项 const compilerOptions: ts.CompilerOptions = { module: ts.ModuleKind.CommonJS, target: ts.ScriptTarget.Latest }; // 创建程序实例(自定义文件读取逻辑适配内存代码) const program = ts.createProgram([fileName], compilerOptions, { getSourceFile: (name) => name === fileName ? sourceFile : undefined, getDefaultLibFileName: () => ts.getDefaultLibFilePath(compilerOptions), writeFile: () => {}, getCurrentDirectory: () => "", getDirectories: () => [], getCanonicalFileName: (name) => name, useCaseSensitiveFileNames: () => true }); // 获取类型检查器 const checker = program.getTypeChecker(); // 遍历AST节点,定位foo函数 function locateFoo(node: ts.Node): ts.FunctionDeclaration | undefined { if (ts.isFunctionDeclaration(node) && node.name?.text === "foo") { return node; } for (const child of node.getChildren()) { const result = locateFoo(child); if (result) return result; } return undefined; } const fooFunc = locateFoo(sourceFile); if (fooFunc) { const funcSymbol = checker.getSymbolAtLocation(fooFunc.name!); if (funcSymbol) { const funcType = checker.getTypeOfSymbolAtLocation(funcSymbol, fooFunc); const callSignature = funcType.getCallSignatures()[0]; const returnType = checker.getReturnTypeOfSignature(callSignature); // 将类型转换为可读文本 console.log(`foo函数的推断返回类型:${checker.typeToString(returnType)}`); // 输出结果:foo函数的推断返回类型:number } }
关键说明
transpileModule会跳过类型检查环节,无法生成类型相关的元数据,因此必须使用createProgram构建完整程序- 通过自定义文件系统接口(
CompilerHost),可以直接处理内存中的代码,无需写入实际文件 TypeChecker是提取类型信息的核心工具,它能解析AST节点对应的符号、类型签名,最终获取推断的返回类型
内容的提问来源于stack exchange,提问作者OrenIshShalom
相关产品推荐
相关产品推荐

