为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

MM们 2022-06-09 19:25:05
这是我想要得到的非常简单的例子。我的问题是关于@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 Baselet sub= Sub.method() // IDE should understand that sub is instance of Sub
查看完整描述

2 回答

?
潇潇雨雨

TA贡献1833条经验 获得超4个赞

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


/** @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();

  }

}


查看完整回答
反对 回复 2022-06-09
?
慕妹3146593

TA贡献1820条经验 获得超9个赞

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

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

以下解决方法在带有 JSDoc 的 Visual Studio Code for JavaScript 中运行良好:

//img1.sycdn.imooc.com//62a1d8b6000146b207180546.jpg

/**

 * @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)


查看完整回答
反对 回复 2022-06-09
  • 2 回答
  • 0 关注
  • 207 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
微信客服

购课补贴
联系客服咨询优惠详情

帮助反馈 APP下载

慕课网APP
您的移动学习伙伴

公众号

扫描二维码
关注慕课网微信公众号