【问题标题】:How to document parameter of class type extending another class with JSDoc?如何用 JSDoc 记录扩展另一个类的类类型的参数?
【发布时间】:2020-04-26 12:13:40
【问题描述】:

假设我有这个定义类的 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 cmets。

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

【问题讨论】:

    标签: javascript eslint jsdoc


    【解决方案1】:

    jsdoc does not document 表示扩展类的类型的任何特殊语法。

    一方面,你可能只使用ParentClass 作为类型(暗示这个接口就是返回的)——考虑到 jsdoc 实际上是一个文档工具而不是一个严格的类型检查器(和 JavaScript 方法通常不仅仅是期望一个特定的(鸭子类型的)接口,而不是强加instanceof 检查等)。

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

    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 没有记录使用带有 @extends 的括号,因为 Closure 显然需要,但我相信它可能适用于括号。)

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-07-18
      • 2013-05-22
      • 2013-04-07
      • 1970-01-01
      • 1970-01-01
      • 2019-10-25
      • 2021-03-22
      • 1970-01-01
      相关资源
      最近更新 更多