Cooluhuru Cooluhuru - 2 months ago 11
TypeScript Question

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

I am trying to figure out how to get this to work correctly:

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

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


So I can do method chaining:

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


Of course, TypeScript complains that
this
doesn't match B's type.

Answer

Simply use the this keyword as the return type of methods that return this:

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

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

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

You can also omit the return types. TypeScript will infer the return types as this because the methods return this:

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

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

This feature is called Polymorphic this types and was introduced in TypeScript 1.7. See the GitHub PR for details.

Comments