Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Define static method as returning instance of current class

Tags:

typescript

I'm wanting to do something like this:

class Base {
   static foo(): <???>; // <= What goes here?
}

class Subclass extends Base {}

Subclass.foo() // <= I want this to have a return type of Subclass, not Base
like image 448
Gaelan Avatar asked Dec 14 '22 14:12

Gaelan


1 Answers

TypeScript has been adding features aggressively over the past year, including support for using class types in generics. This example compiles in 2.3 or later:

interface Constructor<M> {
  new (...args: any[]): M
}

class Base {
  static foo<T extends Base>(this: Constructor<T>): T {
    return new this()
  }
}

class Subclass extends Base {
  readonly bar = 1
}

// Prove we have a Subclass instance by invoking a subclass-specific method:
Subclass.foo().bar
like image 168
mrm Avatar answered Jan 07 '23 09:01

mrm