我想创建一个类,具有接口的所有属性,但实际上并未声明这些属性。接口属性在构建过程中添加,且将在运行时存在。
我找到了这篇文章,指导我使用Partial<T>
……但似乎不起作用。以下代码没有产生编译错误。
interface Animal {
name: string;
}
interface HasConstructor {
constructor: any;
}
//Do this to supress this error: "Type 'Dog' has no properties in common with type 'Partial<Animal>"
type OptionalAnimal = Partial<Animal> & HasConstructor;
class Dog implements OptionalAnimal {
public constructor() {
}
public breed: string;
}
然而,在 Dog 的实例上并不可用
name
属性。var spot = new Dog();
spot.name = "Spot"; //ERROR: Property 'name' does not exist on type 'Dog'
我可以通过创建另一种类型并像这样引用来解决这个问题:
type AnimalDog = Dog & Animal;
var spot: Animal = new Dog() as any;
spot.name = "Spot";
然而,我无法构建一个新的
AnimalDog
实例,并且必须将其强制转换为any
以使类型匹配,因此根据场景,我的代码中使用了AnimalDog
和Dog
两种类型。这还会在引用Animal类型时在Dog内部产生编译错误。有没有一种方法可以告诉TypeScript该类实现了接口,而不需要显式声明每个接口属性?
constructor: any
这个属性的意义是什么?所有对象已经拥有了这个属性。 - Titian Cernicova-DragomirDog
要成为一个类呢?如果你在构建过程中创建了所有内容,那就让它成为接口吧。 - smnbbrveverything
,只是从接口中添加缺失的部分。我的示例与我们的实际情况并不完全相同,但Dog
有它自己的属性,我们实际上需要运行new Dog()
,需要一个具体的类实例。 - TwitchBronBron