首页 > 解决方案 > 如何用 JSDoc 记录扩展另一个类的类类型的参数?

问题描述

假设我有这个定义一个类的 javascript 代码。它的一个静态方法返回一个用于实例化子级的类。

class ParentClass {
  /**
   * Creates an instance of parent class
   *
   * @param {string} type - the type of the instance.
   */
  constructor(type) {
    this.type = type;
  }

  /**
   * Creates a child class.
   *
   * @param {string} type - the type.
   *
   * @returns {class<ParentClass> ?? ----- WHAT GOES HERE?? -----} the resulting class.
   */
  static createChildClass(type) {
    return class extends ParentClass {
      constructor() {
        super(type);
      }
    };
  }

}

我正在使用 eslint 插件eslint-plugin-jsdoc来检查代码中的 JSDoc 注释。

我的问题是:记录从另一个类扩展的类(在 a@param或中)的正确方法是什么?@returns换句话说,我如何记录@returns上面代码中的标记?

标签: javascripteslintjsdoc

解决方案


jsdoc没有记录任何表示扩展类的类型的特殊语法。

一方面,您可能只使用ParentClassas 类型(暗示这个接口就是返回的内容)——考虑到 jsdoc 实际上是一个文档工具而不是一个严格的类型检查器(并且 JavaScript 方法比预期的更常见)一个特定的(鸭子类型的)接口,而不是强加instanceof检查等)。

@augments但是,您可以使用标记(在 jsdoc 中也可以使用,并且在Closure@extends中也需要这样)来提供更精确的返回类型定义:

class ParentClass {

  // ...

  /**
   * Creates a child class.
   *
   * @param {string} type - the type.
   *
   * @returns {ChildClass} the resulting class.
   */
  static createChildClass(type) {
    /**
     * @class ChildClass
     * @augments ParentClass
     */
    return class extends ParentClass {
      constructor() {
        super(type);
      }
    };
  }
}

(IIRC,虽然 jsdoc 没有记录使用@extendsClosure 显然需要的括号,但我相信它可以与括号一起使用。)

但是请注意,这仍然是一个小技巧,因为我们没有记录返回特定实例,但我们想记录返回整个类。有关未实现的问题,请参阅https://github.com/jsdoc/jsdoc/issues/1349。(TypeScript 允许typeof使用类型,例如@returns {typeof ChildClass}.)


推荐阅读