如何使用TypeScript模块API程序化获取TypeScript错误与警告?
问题:程序化检测TypeScript错误时diagnostics返回空数组
我尝试用TypeScript模块程序化检测TypeScript错误,但运行以下代码时,即使代码存在明显的类型错误(Message接口缺少b属性),diagnostics始终输出空数组:
var ts=require('typescript') var file_content=` interface Message{ a:string b:number } var a:Message={a:'hello'} ` var options={ compilerOptions:{ module:'ES2015', target:'ES2015', inlineSourceMap:true }, reportDiagnostics: true } const typescript_output = ts.transpileModule(file_content,options) console.log(typescript_output.diagnostics)
请问获取TypeScript错误的正确TypeScript模块API是什么?
解决方案
ts.transpileModule的设计目标是快速转译单个文件,它不会执行完整的类型检查,因此无法捕获这类类型错误。要获取完整的诊断信息(包括类型错误),需要使用TypeScript的Program API,它会模拟完整的编译流程,包含类型检查环节。
以下是修正后的代码:
const ts = require('typescript'); const fileContent = ` interface Message{ a:string b:number } var a:Message={a:'hello'} `; // 定义编译选项 const compilerOptions = { module: ts.ModuleKind.ES2015, target: ts.ScriptTarget.ES2015, inlineSourceMap: true }; // 模拟内存中的文件 const fileName = 'virtual-file.ts'; const virtualFiles = { [fileName]: fileContent }; // 自定义文件读取器,供TypeScript读取内存中的文件 const customHost = { readFile: (filePath) => virtualFiles[filePath], fileExists: (filePath) => !!virtualFiles[filePath], getCurrentDirectory: () => '', getDirectories: () => [], getCanonicalFileName: (path) => path, getNewLine: () => '\n' }; // 创建Program实例,触发完整编译流程 const program = ts.createProgram([fileName], compilerOptions, customHost); // 获取所有预发射阶段的诊断信息(包含类型错误) const diagnostics = ts.getPreEmitDiagnostics(program); // 格式化并打印错误信息 diagnostics.forEach(diagnostic => { if (diagnostic.file) { const pos = ts.getLineAndCharacterOfPosition(diagnostic.file, diagnostic.start); const errorMsg = ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n'); console.log(`${diagnostic.file.fileName}: 第${pos.line + 1}行,第${pos.character + 1}列: ${errorMsg}`); } else { console.log(ts.flattenDiagnosticMessageText(diagnostic.messageText, '\n')); } });
关键说明
ts.createProgram:创建编译程序实例,需要传入待编译的文件列表、编译选项,以及自定义的文件宿主(用于读取内存中的文件,而非磁盘文件)。ts.getPreEmitDiagnostics:获取编译过程中(发射JS代码前)的所有诊断信息,包括语法错误、类型错误等。- 自定义文件宿主:因为我们的代码是在内存中而非磁盘文件,所以需要实现
readFile、fileExists等方法,让TypeScript能读取到我们的虚拟文件。
运行这段代码后,会正确输出类型错误:
virtual-file.ts: 第6行,第13列: Property 'b' is missing in type '{ a: string; }' but required in type 'Message'.
内容的提问来源于stack exchange,提问作者yigal
相关产品推荐
相关产品推荐

