【问题标题】:type not allowing me to create instances输入不允许我创建实例
【发布时间】:2020-03-09 08:35:41
【问题描述】:

我有一段时间有问题

让我们来吧:

export abstract class abstractClass {
    abstract thing(): string
}

export class c1 extends abstractClass {
    thing(): string {
        return "hello"
    }
}

export class c2 extends abstractClass {
    thing(): string {
        return "world"
    }
}

export interface simpleInter {
    el: typeof abstractClass
}

const cls: simpleInter[] = [];
cls.push({
    el: c1
},{
    el: c2
})

for (const classObj of cls) {
    const c = new (classObj.el)() // error: Cannot create an instance of an abstract class. ts(2511)
    console.log(c.thing())
}

我似乎无法回答的是如何让编译器理解我想要作为扩展我的abstractClass的类型类

【问题讨论】:

    标签: typescript class interface abstract typeof


    【解决方案1】:

    定义一个构造函数接口CConstructor,用它作为你的具体类的基类型而不是typeof abstractClass,你应该很高兴。

    export interface CConstructor {
        new(): abstractClass
    }
    
    export abstract class abstractClass {
        abstract thing(): string
    }
    
    export class c1 extends abstractClass {
        thing(): string {
            return "hello"
        }
    }
    
    export class c2 extends abstractClass {
        thing(): string {
            return "world"
        }
    }
    
    const cls: CConstructor[] = [c1, c2];
    
    for (const classObj of cls) {
        const c = new (classObj)()
        console.log(c.thing())
    }
    

    更新:

    CConstructor 中的new(): abstractClass 称为“构造签名”,可以通过在调用签名前添加new 关键字来创建。欲了解更多信息,请查看new TS handbook page

    【讨论】:

      【解决方案2】:

      到目前为止,我可以理解你想要动态地实例化你的类。 所以这里我可以参考:Dynamic instantiation in JavaScript

      对于自动补全,您可以稍后投射到所需的对象。

      如果这最终对您有所帮助,我不确定,但也许这会让您更接近解决方案:

      interface simpleInter {
        el: string;
      }
      
      const cls: simpleInter[] = [];
      cls.push({
        el: 'c1'
      },{
        el: 'c2'
      });
      
      function instantiate(className: string, args: any) {
        var o, f, c;
        c = window[className]; // get reference to class constructor function
        f = function(){}; // dummy function
        f.prototype = c.prototype; // reference same prototype
        o = new f(); // instantiate dummy function to copy prototype properties
        c.apply(o, args); // call class constructor, supplying new object as context
        o.constructor = c; // assign correct constructor (not f)
        return o;
      }
      
      for (const classObj of cls) {
        const c = instantiate(classObj.el, []); // error: Cannot create an instance of an abstract class. ts(2511)
        console.log(c.thing());
      }
      

      【讨论】:

        猜你喜欢
        • 2016-07-26
        • 2012-12-19
        • 2023-03-12
        • 1970-01-01
        • 2021-07-12
        • 1970-01-01
        • 2016-10-03
        • 2013-06-19
        • 1970-01-01
        相关资源
        最近更新 更多