Class TypeScript:如何获取子类';s方法返回此父对象

Class TypeScript:如何获取子类';s方法返回此父对象,class,typescript,method-chaining,Class,Typescript,Method Chaining,我正试图找出如何使其正常工作: class A { john(): B { return this; // <-- ERROR HERE } } class B extends A { joe(): B { return this; } } 当然,TypeScript抱怨this与B的类型不匹配。只需使用this关键字作为返回this的方法的返回类型: class A { john(): this {

我正试图找出如何使其正常工作:

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

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

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

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

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

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

let instance = new B();
instance.john().joe();
class A {
    john() {
        return this;
    }
}

class B extends A {
    joe() {
        return this;
    }
}
您还可以省略返回类型。TypeScript将推断返回类型为
this
,因为方法返回
this

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

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

let instance = new B();
instance.john().joe();
class A {
    john() {
        return this;
    }
}

class B extends A {
    joe() {
        return this;
    }
}
此功能在TypeScript 1.7中被调用和使用。有关详细信息,请参阅。

您不需要“父项this”,因为a B也是a。