How do you subclass a generic Class expression with constructor overload

314 views Asked by At

Angular's FormControl<T> is defined as class expression with constructor overload in an interface. This is due to a typescript limitation.

I was able to narrow the code down to :

export interface FormControl<TValue = any> {
  setValue(value: TValue): void;
}

export interface ɵFormControlCtor {
  new <T>(): FormControl<T>;
  new <T>(): FormControl<T | null>;

  prototype: FormControl<any>;
}

export const FormControl: ɵFormControlCtor = (class FormControl<T> {
  setValue(value: T): void { }
});

Unfortunatly, subclassing FormControl<T> triggers a TS2510 Base constructors must all have the same return type.

There is already another question, related to this error but the suggestion solutions don't work with a generic type.

So how would you subclass FormControl ?

Maybe it's somehow possible to also do another class expression to subclass it ?

Playground

1

There are 1 answers

1
Alykam Burdzaki On BEST ANSWER

I'm not sure if this is enough for you, but it works if your generic type fullfills all the overloads:

class Foo<T> extends FormControl<T | null> {

}

playground