[英]How to use the TypeScript Compiler API to type-check modules imported using `require()`?
我正在使用TypeChecker
编译器 API中的 TypeChecker,以便为我的程序的 AST 中的每个节点提取(推断)类型信息。 特别是,我尝试从导入的模块函数中找出返回值,例如:
var vec3 = require('gl-matrix/vec3')
var myVec = vec3.fromValues(1, 2, 3) // $ExpectedType vec3
这适用于使用import { … } from '…'
语句导入的模块,但不幸的是,无法正确识别使用上述require()
导入的模块,我只接收它们的类型any
。 但是,我设置了两个编译器选项allowJs
和checkJs
。
为什么没有正确推断出require()
d 模块的类型? VS Code(AFAIK 依赖于相同的 API?)也能够从require()
语句中推断出类型,所以我猜一般来说,tsc 能够处理它们。 我需要以不同方式设置任何其他编译器选项吗? 或者这确实不支持,我需要为此使用其他一些 package?
这是一个最小的重现脚本,我也把它和两个示例文件放在 repl.it 上: https://replit.com/@LinqLover/typecheck-js
var ts = require("typescript")
// Run `node index.js sample-import.js`` to see the working TypeScript analysis
const files = process.argv[1] != "/run_dir/interp.js" ? process.argv.slice(2) : ["sample-require.js"]
console.log(`Analyzing ${files}:`)
const program = ts.createProgram(files, {
target: ts.ScriptTarget.ES5,
module: ts.ModuleKind.CommonJS,
allowJs: true,
checkJs: true
})
const checker = program.getTypeChecker()
for (const sourceFile of program.getSourceFiles()) {
if (!sourceFile.isDeclarationFile) {
ts.forEachChild(sourceFile, visit)
}
}
function visit(node) {
try {
const type = checker.getTypeAtLocation(node)
console.log(checker.typeToString(type))
} catch (e) {
// EAFP
}
ts.forEachChild(node, visit)
}
非常感谢您!
对于后续工作,这被证明是gl-matrix
的类型定义的问题。 在怀疑 TypeScript 引擎本身可能被破坏之前,我最好先尝试多个包......
gl-matrix
问题: https://github.com/toji/gl-matrix/issues/429
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.