首页 > 解决方案 > typeof 类或其任何子类,而不是类的实例

问题描述

我有这些课程

class Foo {}

class A extends Foo {}

class B extends Foo {}

现在我想创建一个接口,type它的类型是类而不是类的实例

interface Bar {
    type  : XXXX;     // I don't know to put here
    value : string;
}

所以我可以像这样创建该接口的实例

const x : Bar = {
    type  : Foo, // or and of its subclasses for example A or B
    value : 'test',
}

我不想要一个实例,而是Foo一个类Foo

{
    type : new Foo(),
    value : "test"
}

不应该是有效的

我希望我正确地解释了我的问题

标签: typescript

解决方案


看起来您只需要form的构造签名new () => Foo,意思是“产生类型实例的零参数构造函数Foo”。像这样:

interface Bar {
     type: new () => Foo;
     value: string;
}

const x: Bar = {
     type: Foo,
     value: 'test',
};
const y: Bar = {
     type: A,
     value: ""
};
const z: Bar = {
     type: new Foo(), // error!
//   ~~~~ <-- // Type 'Foo' is not assignable to type 'new () => Foo'.
     value: ""
}

Playground 代码链接


推荐阅读