Class method which returns an array of itself. How to annotate and inherit? Class method which returns an array of itself. How to annotate and inherit? typescript typescript

Class method which returns an array of itself. How to annotate and inherit?


Specify this[] as the return type of your method:

class PageElement {  getAll(): this[]  {}}class InputElement extends PageElement {  aSpecificInputElementMethod() {}}const inputElement = new InputElement();const inputElements = inputElement.getAll();inputElements[0].aSpecificInputElementMethod(); // valid;

See it in action on TS Playground.


Not actually an ideal way, but you can specify the return type as the type argument

getAll<T>(): T[]

And then call like

getAll<InputElement>

The downsides are:

  • You need to specify type argument every time you call getAll
  • Type argument should always be a valid type
  • You can pass any type of an argument

So basically there is not a lot of type safety because it’s up to you to keep the type argument valid every time you call getAll.This will probably cause issues if you are working in a team.

Maybe someone can suggest a way on how to restrict generic type to be an instance of this particular type.