首页 > 解决方案 > TypeScript 静态成员返回相同的类实例?

问题描述

如何声明find方法的返回类型?

class Base{
  find(){
    return new this()
  }
}

作为find返回 self 类实例,它不能硬编码为:Base. 例如,如果我Child从 Base 继承类而不是 Child.find() 必须返回Child类型,而不是Base.

class Base{
  static find(): Base{  // this is incorrect
    return new this()
  }
}

我尝试使用下面的通用但得到 TS2302 错误。那么正确的方法是什么?

class Base<T>{
  static find(): T{  // ERROR: TS2302
    return new this()
  }
}

标签: typescriptgenericstypescript-typings

解决方案


正如这个重复的问题的答案中提到的,TypeScript中的方法或成员目前没有多态;thisstatic有关详细信息,请参阅microsoft/TypeScript#5863

解决方法是使静态方法通用并给它一个this参数

class Base {
    static find<T extends Base>(this: new () => T): T {
        return new this(); // no-arg constructor
    }
}

这应该如你所愿:

class GoodSub extends Base {
    foo = "bar";
}
const goodSub = GoodSub.find(); // GoodSub
console.log(goodSub.foo.toUpperCase()); // BAR

如果您尝试在其构造函数需要参数的子类上使用它,它会抱怨:

class BadSub extends Base {
    constructor(public bar: string) {
        super();
    }
}
const badSub = BadSub.find(); // error!
// ----------> ~~~~~~
// typeof BadSub is not assignable to new () => BadSub
console.log(badSub.bar.toUpperCase());  // error at runtime, badSub.bar is undefined

好的,希望有帮助;祝你好运!Playground 代码链接


推荐阅读