Edward Liang Edward Liang - 1 year ago 111
TypeScript Question

How to specify derived class with type annotation in typescript 2?

I was stuck with an "Cannot create an instance of the abstract class 'AbtCls'" in with such code:

In ambient declaration for ModuleA, :

declare function f(a: Function): AbtCls;
export = f;

In normal code:

let a = ModulaA('');
let c = new a(); // Error: "Cannot create an instance of the abstract class 'AbtCls'"

The ModuleA would return an unamed subclass, but TS only check against the abstract superclass.

Here I cannot changed the external ModuleA's implementation meanwhile not to constrict to only one derived implemented class.

Is there any way to specify all derived classes of AbtCls in the type annotation?

Answer Source

Instead of declaring the return type to be the abstract class, instead define the return type to be a constructor that returns an instance of the class:

declare function f(a: Function): new() => AbtClsInstanceType;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download