猿问

jsdoc 如何描述返回 SAME CLASS 变量的静态类方法

这是我想要得到的非常简单的例子。我的问题是关于@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


MM们
浏览 208回答 2
2回答

潇潇雨雨

没有“相对”类型。您可以相当简单地修改扩展类;/** @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();  }}

慕妹3146593

我知道这是一个非常古老的问题,在大多数情况下,对于静态方法需要多态 this 的项目现在将使用 TypeScript 和此处列出的解决方法。我们的几个基于浏览器的项目仍在使用纯 ES 模块 JavaScript,没有任何构建步骤,并且为此用例引入构建步骤似乎是最重要的。在这些项目中,我们还使用 Visual Studio Code 的“隐式项目配置:检查 JS”来启用类型检查。必须强制转换每个扩展静态方法的返回值是一件非常痛苦的事情!以下解决方法在带有 JSDoc 的 Visual Studio Code for JavaScript 中运行良好:/**&nbsp;* @template&nbsp; T&nbsp;* @param {T} Class&nbsp;* @returns {{&nbsp;*&nbsp; &nbsp;method: () => InstanceType<T>&nbsp;*&nbsp; } & T}&nbsp;*/// @ts-ignoreconst fixPolymorphicThis = Class => Classclass Base {&nbsp; &nbsp; static method() {&nbsp; &nbsp; &nbsp; &nbsp; return new this()&nbsp; &nbsp; }}const Sub = fixPolymorphicThis(class Sub extends Base { })let base = Base.method() // IDE should understand that base is instance of Baselet sub = Sub.method() // IDE should understand that sub is instance of Subconsole.assert(sub instanceof Base)console.assert(sub instanceof Sub)
随时随地看视频慕课网APP

相关分类

JavaScript
我要回答