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

Viewed 57

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?

2 Answers

I'm not sure if this is what you want but you can use recursive constraint:

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

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

const subclass = new SubClass().returnSelf()

Playground

Related