javascript - 为现有 JSDOC 注释的 commonJS 库创建 Typescript 声明文件
问题描述
我有一个问题,我无法使用 typescript 4.0 为 commonJS 格式的 jsdoc 注释 javascript 库创建声明文件 (d.ts)。
如果在我运行 typescript 编译器来创建 d.ts 文件时,多个模块需要一个或多个对象,我会收到此错误:
index.js:1:1 - error TS9006: Declaration emit for this file requires using private name 'Rectangle' from module '"/Users/gabry/projects/ts-test/rectangle"'. An explicit type annotation may unblock declaration emit.
1 const {Rectangle} = require('./rectangle');
~~~~~
Found 1 error.
我可以通过在 rectangle.js 中的类之前添加“导出”来“修复”它,但这样代码在 node.js 下就不再可运行了......
我已经看到 typescript 中有一个关于类似https://github.com/microsoft/TypeScript/issues/9865的错误,应该在 typescript 4.1 beta 中解决,但也安装该版本的 typescript 我有同样的问题,也许我使用 commonJS require/module.exports 的方式有问题?
这是一个示例:
index.js
const {Rectangle} = require('./rectangle');
class Render {
constructor() {
/**
* Object list
* @type {Rectangle[]}
*/
this.objects = [];
}
/**
* Adds a rectangle
*
* @returns {Rectangle} the rect
*/
addRectangle() {
const obj = new Rectangle();
this.objects.push(obj);
return obj;
}
}
module.exports = { Render }
矩形.js
class Rectangle {
constructor() {
console.log("I'm a rectangle!");
}
}
module.exports = { Rectangle };
这是tsconfig.json:
{
// Change this to match your project
"files": ["index.js"],
"compilerOptions": {
"allowJs": true,
"declaration": true,
"emitDeclarationOnly": true,
"outDir": "types",
"strict": false
}
}
我尝试添加/更改大量 tsconfig.json 参数(目标、模块、moduleResolution ......)但没有成功......
我可以通过带有节点的简单测试脚本毫无问题地运行它:
测试.js
const {Render} = require("./index");
let render = new Render();
render.addRectangle();
console.log("Objects", render.objects);
node test.js
...按预期返回:
I'm a rectangle!
Objects [ Rectangle {} ]
解决方案
这现在在 typescript 4.1 的发布版本中得到了修复,这确实是 typescript 编译器的一个 bug,它在只发出声明时发生,typescript 4.1 的第一个 beta 仍然有这个 bug,但某个时刻开始出现已修复(有关详细历史记录,请参阅原始问题中的错误),最终在 npm 注册表上发布了最终的、有效的 v4.1。
所以如果有人仍然有这个问题,它可以简单地将他的 typescript 依赖更新到最新的稳定版本( ^4.1 )。