如何通过编程提取VS Code中TypeScript的tooltip信息?
如何程序化生成VS Code悬停显示的函数类型提示
要生成你示例中VS Code展示的函数返回类型提示,本质是让脚本获取TypeScript对函数的类型推断结果并格式化输出,以下是两种可靠的实现方式:
方法一:直接使用TypeScript Compiler API
这是最原生的方案,利用TypeScript自带的编译工具链分析代码:
- 先确保项目已安装TypeScript:
npm init -y && npm install typescript @types/node - 创建分析脚本(比如命名为
generate-type.ts):import * as ts from 'typescript'; import * as fs from 'fs'; // 读取你的函数文件内容 const targetFilePath = './your-function-file.ts'; const code = fs.readFileSync(targetFilePath, 'utf8'); // 配置TypeScript编译选项 const compilerOptions: ts.CompilerOptions = { target: ts.ScriptTarget.ESNext, module: ts.ModuleKind.CommonJS, strict: true, esModuleInterop: true, allowSyntheticDefaultImports: true, }; // 创建编译程序实例 const program = ts.createProgram([targetFilePath], compilerOptions); const typeChecker = program.getTypeChecker(); // 遍历文件找到目标函数 program.getSourceFiles().forEach(sourceFile => { ts.forEachChild(sourceFile, node => { if (ts.isFunctionDeclaration(node) && node.name?.getText() === 'getInfra') { const functionSignature = typeChecker.getSignatureFromDeclaration(node); if (functionSignature) { // 获取并格式化返回类型 const returnType = typeChecker.typeToString( typeChecker.getReturnTypeOfSignature(functionSignature), node, ts.TypeFormatFlags.NoTruncation | ts.TypeFormatFlags.UseAliasDefinedOutsideCurrentScope ); // 输出类似VS Code的提示格式 console.log(`function getInfra(): ${returnType}`); } } }); }); - 运行脚本:
npx ts-node generate-type.ts
方法二:使用ts-morph简化开发
ts-morph是对TypeScript Compiler API的封装,语法更简洁,降低上手成本:
- 安装依赖:
npm install ts-morph typescript @types/node - 创建脚本:
import { Project } from 'ts-morph'; const project = new Project({ compilerOptions: { target: 'ESNext', strict: true, esModuleInterop: true, }, }); // 加载目标文件 const sourceFile = project.addSourceFileAtPath('./your-function-file.ts'); // 定位到getInfra函数 const getInfraFunc = sourceFile.getFunction('getInfra'); if (getInfraFunc) { // 获取返回类型的文本表示 const returnTypeText = getInfraFunc.getReturnType().getText(); // 输出格式化结果 console.log(`function getInfra(): ${returnTypeText}`); } - 运行脚本:
npx ts-node generate-type.ts
注意事项
- 两种方案都依赖TypeScript的类型检查能力,所以你的代码需要是合法的TypeScript文件,或是开启了
allowJs和checkJs选项的JavaScript文件 - 可以通过调整
TypeFormatFlags(Compiler API)或ts-morph的相关配置,控制输出类型的格式(比如是否展开嵌套类型、是否保留别名等) - 如果你用的是JavaScript项目,需要在
tsconfig.json中添加如下配置:{ "compilerOptions": { "allowJs": true, "checkJs": true, "strict": true } }
内容的提问来源于stack exchange,提问作者Truman Purnell
相关产品推荐
相关产品推荐

