Home > Net >  Can method in interface return type of "this"?
Can method in interface return type of "this"?

Time:01-24

Example code:

interface IBuilder {
  build(): this; // Builder?
}

class Builder implements IBuilder {
  ...
  public build(): this {
    ...
    return this;
  }
}

Question in topic.

Will it work the same as if method returned type of Builder?

CodePudding user response:

this simply refers to the current instance of the object. If the class Builder is instantiated, this will refer to Builder but that does mean it's always Builder since other classes can extend Builder and subsequently this will refer to the new instance type.

Will it work the same as if method returned type of Builder?

Not necessarily, see playground

CodePudding user response:

I believe it doesn't work the way you intend it to, take a look at this Playground

The problem is that using this in the interface definition will not allow you to return just any instance of Builder but this current instance.

If you wanted, you could make IBuilder generic, which will allow you to define the return type of build() in the class definition:

interface IBuilder<T> {
  build(): T;
}

class Builder implements IBuilder<Builder> {
  public build() { // You can omit the type here, since it's defined through the interface.
    // return this;
    return new Builder(); // Both of these will work.
  }
}
  • Related