是否存在一种非实例化类?

neh*_*ist 2 typescript

假设以下代码:

interface Foobar {}

class Foo implements Foobar {}
class Bar implements Foobar {}

const arr: Foobar[] = [Foo, Bar];
Run Code Online (Sandbox Code Playgroud)

这可以编译,事实并非如此。typeof Foo或者typeof BarFunction- 是有道理的,因为到目前为止它们还没有被实例化。

有没有比存储非实例化类更好的方法arr: any[]

Rya*_*ugh 5

这里空荡荡的界面让你感到厌烦;此代码仅“有效”,因为该接口没有成员(因此意味着“任何内容”):

interface Foobar { x: number; }

class Foo implements Foobar { x: number; }
class Bar implements Foobar { x: number; }

// Error
const arr: Foobar[] = [Foo, Bar];
Run Code Online (Sandbox Code Playgroud)

类的一般类型是{ new(...args: any[]): any }如果您正在谈论可以使用 调用的东西new,或者{ new(...args: any[]): Foobar }如果您正在谈论Foobar使用 调用时返回 a 的东西new