Typescript return typeof this

Viewed 119

I'm looking for the correct way of returning the type of this from an implementation of an abstract method. Like the self in PHP.

I've tried this very basic example:

abstract class Listable {
  public abstract list(): (typeof this)[]; //bad syntax
}

class SomeList extends Listable {
  public list(): SomeList[] {
    return [new SomeList, new SomeList, new SomeList];
  }
}

This is - however - bad syntax. Is there a way to do this?

1 Answers

You can just use a this type as follows:

abstract class Listable {
  public abstract list(): this[];
}

class SomeList extends Listable {
  public list(): this[] {
    return [this];
  }
}

const l = new SomeList().list(); // type of l is SomeList[]
Related