How to do a covariant generic return type in a method?

G9QV2

I have an interface that I want to have a method that returns an instance of the implementing class, my current implementation is this:

interface SuperClass<T extends SuperClass<any>> {
  returnSelf(): T; 
}

class SubClass implements SuperClass<SubClass> {
  public returnSelf(): SubClass {
    return this;
  }
}

const subclass: SubClass = new SubClass().returnSelf();

However, this uses the any type, which I know is supposed to be avoided at all costs. My question is, is this typesafe? I can't think of any case in which it wouldn't be, but I would like to rather use the safer unknown type, however that doesn't compile. Why? Is there a more idiomatic way of doing this?

PotatoesMaster

You can use this as a type.
https://www.typescriptlang.org/docs/handbook/advanced-types.html#polymorphic-this-types

interface SuperClass {
  returnSelf(): this;
}

class SubClass implements SuperClass {
  public returnSelf(): this {
    return this;
  }
}

const subclass: SubClass = new SubClass().returnSelf();

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related