【问题标题】:Create Typescript declaration files for existing JSDOC annotated commonJS library为现有 JSDOC 注释的 commonJS 库创建 Typescript 声明文件
【发布时间】:2021-02-04 04:04:54
【问题描述】:

我有一个问题,我无法使用 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 中的类之前添加“export”来“修复”它,但是这样代码在 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 }

rectangle.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...)但没有成功...

我可以通过带有节点的简单测试脚本毫无问题地运行它:

test.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 {} ]

【问题讨论】:

    标签: javascript node.js typescript jsdoc commonjs


    【解决方案1】:

    这个问题现在在 typescript 4.1 的发布版本中得到了修复,它确实是 typescript 编译器的一个 bug,在只发出声明时发生,typescript 4.1 的第一个 beta 版仍然有这个 bug,但是每晚的某个点开始修复(有关详细历史记录,请参阅原始问题中的错误),最终在 npm 注册表上发布了最终的工作 v4.1。

    所以如果有人仍然有这个问题,它可以简单地将他的 typescript 依赖更新到最新的稳定版本 (^4.1)。

    【讨论】:

      猜你喜欢
      • 2014-01-24
      • 1970-01-01
      • 2015-10-04
      • 2018-07-21
      • 2015-06-02
      • 2016-05-12
      • 2017-10-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多