我有一个类的数组,所有这些类都从一个基础抽象类扩展而来。如果你能原谅那些可怕的和过度使用的面向对象抽象:
abstract class Animal {
abstract speak(): string;
}
class Dog extends Animal {
speak(): string {
return "woof... sigh"
}
}
class Cat...我有一个封装了所有这些实现的数组:
const all = [Cat, Dog];我想告诉TypeScript,这个数组中的所有内容在构造时都将返回一个作为Animal实例的类。
重要的是要注意,这是传递类,而不是对象,所以这是无效的,因为类本身不是从抽象继承的。
const all : Array<Animal> = [Cat, Dog]不幸的是,我似乎在文档中找不到任何关于通过new关键字输入提示的内容。
发布于 2020-07-08 20:54:54
我们希望声明一个值,当使用new调用该值时,将返回一个Animal。这是这样写的:
new() => Animal注意与函数类型(() => Animal)的相似性。
完整的代码是:
const all: Array<new() => Animal> = [Cat, Dog];或者,为了清晰起见,使用一个界面:
interface AnimalConstructor {
new(): Animal;
}
const all: AnimalConstructor[] = [Cat, Dog];发布于 2020-07-08 20:31:33
你应该能够做到这一点:
const all: (typeof Animal)[] = [Cat, Dog]https://stackoverflow.com/questions/62794344
复制相似问题