TypeScript:如何让子类的方法成为 return 的父类

TypeScript: How to get a subclass's method to return parent this

我正在想办法让它正常工作:

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

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

所以我可以进行方法链接:

let instance = new B();
instance.john().joe(); 

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

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

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

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

let instance = new B();
instance.john().joe();

您也可以省略 return 类型。 TypeScript 会将 return 类型推断为 this 因为方法 return this:

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

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

有关详细信息,此功能称为 Polymorphic this types and was introduced in TypeScript 1.7. See the GitHub PR