输入不允许我创建实例

type not allowing me to create instances

我遇到问题有一段时间了

让我们有这个:

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

到目前为止,我不明白您想动态地实例化您的类。 所以在这里我可以参考: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());
}

定义构造函数接口 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称为"Construct Signature",可以通过在调用签名前添加new关键字来创建。有关更多信息,请查看 new TS handbook page.