TypeScript:如何获取子类的方法来返回父类

Ant*_*Ant 3 class method-chaining typescript

我试图弄清楚如何让它正常工作:

class A {
    john(): B {
        return this; // <-- ERROR HERE
    }
}

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

所以我可以做方法链接:

let instance = new B();
instance.john().joe(); 
Run Code Online (Sandbox Code Playgroud)

当然,TypeScript抱怨this与B的类型不匹配.

Mic*_*Liu 7

只需使用this关键字作为返回方法的返回类型this:

class A {
    john(): this {
        return this;
    }
}

class B extends A {
    joe(): this {
        return this;
    }
}

let instance = new B();
instance.john().joe();
Run Code Online (Sandbox Code Playgroud)

您还可以省略返回类型.TypeScript将推断返回类型,this因为方法返回this:

class A {
    john() {
        return this;
    }
}

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

此功能称为多态this类型,并在TypeScript 1.7 中引入.有关详细信息,请参阅GitHub PR.