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();
}
}

TA贡献1820条经验 获得超9个赞
我知道这是一个非常古老的问题,在大多数情况下,对于静态方法需要多态 this 的项目现在将使用 TypeScript 和此处列出的解决方法。
我们的几个基于浏览器的项目仍在使用纯 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)
添加回答
举报