Typescript: instance of an abstract class

后端 未结 1 1425
心在旅途
心在旅途 2020-12-11 21:00

Ok. this is very simple, just to remove an annoying error message.

I have an abstract class Router:

export abstract class Router {
}
<
相关标签:
1条回答
  • 2020-12-11 21:21

    When you have an abstract class, it's constructor is only invokable from a derived class, since the class is abstract and should not be instantiated. This carries over when you type something as typeof AbstractClass, the constructor will not be callable.

    The solution would to be to not use typeof Router but rather a constructor signature that returns a Router

    interface IModule {
        name: string;
        forms: Array<IForm>,
        route: new () => Router
    }
    

    Another solution if you need to access static methods of Router is to create an interface derived from typeof Router which will erase the abstractness of the constructor:

    export abstract class Router {
        static m(): void { console.log("Router"); }
    }
    type RouterClass = typeof Router;
    interface RouterDerived extends RouterClass { }
    
    interface IModule {
        name: string;
        route: RouterDerived
    }
    
    export class Module1 extends Router {
        static m(): void { console.log("Module1"); }
    }
    
    let module: IModule = { 
        name: "My Module",
        route: Module1
    }
    
    module.route.m();
    let router = new module.route(); 
    
    0 讨论(0)
提交回复
热议问题