【问题标题】:TypeScript static member returns same class instance? [duplicate]TypeScript 静态成员返回相同的类实例? [复制]
【发布时间】:2023-03-15 14:50:02
【问题描述】:

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

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

由于find 返回自我类实例,它不能硬编码为:Base。例如,如果我从 Base 继承 Child 类,则 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()
  }
}

【问题讨论】:

    标签: typescript generics typescript-typings


    【解决方案1】:

    正如the question this duplicates 的回答中提到的,TypeScript 中目前没有polymorphic this 用于static 方法或成员;请参阅microsoft/TypeScript#5863 了解更多信息。

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

    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 link to code

    【讨论】:

      猜你喜欢
      • 2015-05-31
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-08-23
      • 1970-01-01
      • 2013-07-27
      • 1970-01-01
      相关资源
      最近更新 更多