使用TypeScript Compiler API生成导入URL类型声明时类型检查返回any如何解决
问题根因
TypeScript 的类型检查器只会在 Program 初始化阶段对所有已存在的源文件 AST 做一次全量类型推导,你动态生成的类型别名节点没有被纳入当前 Program 的检查范围,同时导入表达式的类型解析依赖完整的模块解析链路,未注册的节点不会触发模块解析逻辑,因此返回 any。VS Code 能识别是因为你把生成的内容写入了磁盘,VS Code 的 TS 服务会重新加载文件做全量检查。
解决方法
方法1:更新 Program 后再提取类型
- 将你生成的类型别名节点插入到对应源文件的
statements数组中 - 使用修改后的所有源文件重新初始化
ts.Program实例 - 用新 Program 的类型检查器调用
checker.getTypeAtLocation(t)即可获取正确类型
// 假设原sourceFile是你要插入类型别名的源文件 const updatedSourceFile = ts.factory.updateSourceFile(sourceFile, [ ...sourceFile.statements, t // 你的类型别名节点 ]); // 重新创建Program const newProgram = ts.createProgram([updatedSourceFile.fileName], compilerOptions, host); const newChecker = newProgram.getTypeChecker(); const correctType = newChecker.getTypeAtLocation(updatedSourceFile.statements.at(-1)!);
方法2:直接获取导入模块的 default 导出类型
如果你只是需要拿到 typeof import("somepath").default 的类型,可以跳过生成类型别名的步骤,直接用现有类型检查器解析导入模块:
const importPath = "somepath"; // 先解析模块路径 const resolvedModule = ts.resolveModuleName( importPath, sourceFile.fileName, compilerOptions, ts.sys ).resolvedModule; if (!resolvedModule) return; // 获取模块符号 const moduleSymbol = checker.getSymbolAtLocation( ts.createStringLiteral(resolvedModule.resolvedFileName) ); if (!moduleSymbol?.exports?.has("default")) return; // 取default导出的类型 const defaultSymbol = moduleSymbol.exports.get("default")!; const targetType = checker.getTypeOfSymbolAtLocation(defaultSymbol, sourceFile);
额外注意事项
- 建议替换已废弃的
ts.createXXX系列 API 为ts.factory.createXXX,旧 API 在 TS 4.0+ 版本中已不再维护,可能出现类型节点生成异常的问题 - 确保
somepath符合你当前配置的模块解析规则,存在对应的类型定义文件,避免模块解析失败导致类型为 any
内容的提问来源于stack exchange,提问作者Dor Ben Baruch
相关产品推荐
相关产品推荐

