【问题标题】:How jsdoc describes static class method which returns SAME CLASS variablejsdoc 如何描述返回 SAME CLASS 变量的静态类方法
【发布时间】:2020-07-13 18:00:39
【问题描述】:

这是我想要得到的非常简单的示例。我的问题是关于@returns 标签。我应该在那里写什么?

class Base{
  /**
  * @returns {QUESTION: WHAT SHOUL BE HIRE??}
  */
  static method(){
    return new this()
  }
}

class Sub extends Base{
}

let base= Base.method() // IDE should understand that base is instance of Base
let sub= Sub.method() // IDE should understand that sub is instance of Sub

【问题讨论】:

  • 不幸的是,我相信没有办法做到这一点。

标签: javascript jsdoc


【解决方案1】:

没有“相对”类型。 您可以相当简单地修改扩展类;

/** @extends {Base} */
class Sub extends Base{
  /**  @returns {Sub} */
  static method(){
    return super.method();
  }
}

或者也许使用第三种类型,@interface 来定义此方法的存在

/** @interface */
class I {
  method() {}
}
/** @implements {I} */
class Base {
  /**  @returns {I} */
  static method(){
    return new this();
  }
}

/** 
 * @extends {Base}
 * @implements {I}
 */
class Sub {
  /**  @returns {I} */
  static method(){
    return new this();
  }
}

【讨论】:

    【解决方案2】:

    我知道这是一个非常古老的问题,在大多数情况下,对于静态方法需要多态 this 的项目现在将使用 TypeScript 和here 中列出的解决方法。

    我们的几个基于浏览器的项目仍在使用纯 ES 模块 JavaScript,没有任何构建步骤,并且为这个用例引入构建步骤似乎太过分了。在这些项目中,我们还使用 Visual Studio Code 的“隐式项目配置:检查 JS”来启用类型检查。必须强制转换每个扩展静态方法的返回值是一件非常痛苦的事情!

    以下解决方法在带有 JSDoc 的 Visual Studio Code for JavaScript 中效果很好:

    /**
     * @template  T
     * @param {T} Class
     * @returns {{
     *   method: () => InstanceType<T>
     *  } & T}
     */
    // @ts-ignore
    const fixPolymorphicThis = Class => Class
    
    class Base {
        static method() {
            return new this()
        }
    }
    const Sub = fixPolymorphicThis(class Sub extends Base { })
    
    let base = Base.method() // IDE should understand that base is instance of Base
    let sub = Sub.method() // IDE should understand that sub is instance of Sub
    
    console.assert(sub instanceof Base)
    console.assert(sub instanceof Sub)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-09
      • 2021-07-17
      • 1970-01-01
      • 2020-10-22
      • 1970-01-01
      • 2012-09-30
      • 2012-06-24
      • 1970-01-01
      相关资源
      最近更新 更多