打字稿:抽象类的实例 [英] Typescript: instance of an abstract class

查看:24
本文介绍了打字稿:抽象类的实例的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

好的.这个很简单,就是去掉一个烦人的错误提示.

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

我有一个抽象类路由器:

I have an abstract class Router:

export abstract class Router {
}

还有这样的界面

interface IModule {
    name: string;
    forms: Array<IForm>,
    route: typeof Router
}

现在我有一个看起来像这样的类,还有许多其他基于路由器抽象的类

Now I have a class which looks like this, and many others based on Router abstract

export class Module1 extends Router {
}

现在,我想像这样实例化路线:

Now, I want to instantiate the route like this:

let module: IModule = { 
    name: "My Module",
    forms: [],
    route: Module1
}

let router = new module.route(); 
// TS2511: Cannot create an instance of an abstract class.

代码运行正常,并且router = new Module1()的实例制作正确,但我显然没有在Typescript中正确编写它,因为我看到TS2511:无法创建抽象类的实例. 转译时.

The code run just fine, and the instance of router = new Module1() is made properly, but I obviously doesn't write it properly in Typescript because I see TS2511: Cannot create an instance of an abstract class. when transpiling.

定义这个的正确方法是什么?

What is the correct way to define this?

谢谢

推荐答案

当您有一个抽象类时,它的构造函数只能从派生类调用,因为该类是抽象的,不应实例化.当您键入 typeof AbstractClass 时,此构造函数将不可调用.

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.

解决方案是不使用 typeof Router 而是使用返回 Router

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
}

如果你需要访问 Router 的静态方法,另一种解决方案是创建一个派生自 typeof 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(); 

这篇关于打字稿:抽象类的实例的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆