如何从超类方法而不是超类类型返回子类型

Ale*_*lls 3 generics typescript typescript-generics typescript2.0

我认为这是正确实现泛型的问题,但我不确定。

我在这里创建了一个代表问题的 Github 要点:https : //gist.github.com/ORESoftware/66b72b4b85262d957cb03ad097e4743e

假设我有这个超类:

  class A {

    foo(): A {
      return this;
    }

  }
Run Code Online (Sandbox Code Playgroud)

和几个子类,例如一个看起来像这样:

   class B extends A {

     bar(): B {
      return this;
     }

   }
Run Code Online (Sandbox Code Playgroud)

所以如果我这样做

new B().foo().bar()

这将在运行时工作,但不能使用 TypeScript 进行编译。那是因为foo()将返回类型声明为A,而不是 type B

我怎样才能返回类型this,而不是声明foo()总是返回类型A

我试过这个:

在此处输入图片说明

但我收到此错误:

在此处输入图片说明

Sha*_*ard 5

您必须this使用多态返回此类型的类型

abstract class A {
    foo(): this {
        return this;
    }
}

class B extends A {
    bar(): this {
        return this;
    }
}
Run Code Online (Sandbox Code Playgroud)

这将允许

const b = new B();

b.foo().bar();
Run Code Online (Sandbox Code Playgroud)