【问题标题】:TypeScript: How to get a subclass's method to return parent thisTypeScript:如何获取子类的方法以返回父类
【发布时间】:2016-09-25 03:23:29
【问题描述】:

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

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 的类型不匹配。

【问题讨论】:

  • 你不需要“parent this”,因为 B 也是 A。

标签: class typescript method-chaining


【解决方案1】:

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

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

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

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

您也可以省略返回类型。 TypeScript 将推断返回类型为this,因为方法返回this

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

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

此功能称为 Polymorphic this types,在 TypeScript 1.7 中为 introduced。详情请见GitHub PR

【讨论】:

    猜你喜欢
    • 2021-07-28
    • 2019-04-16
    • 1970-01-01
    • 2021-04-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多