Ant
Ant

Reputation: 1852

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.

Upvotes: 3

Views: 1372

Answers (1)

Michael Liu
Michael Liu

Reputation: 55499

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.

Upvotes: 9

Related Questions