下面的代码中的抽象类true
需要使用抽象属性ParentClass
(这是类的实例,继承自抽象significantEntity
)。当然,下面的代码无效,因为SignificantEntityParent
实现的类型与significantEntity
不同。
SignificantEntityParent
我尝试了使用抽象泛型方法abstract class SignificantEntityParent {}
class SignificantEntity1 extends SignificantEntityParent {}
class SignificantEntity2 extends SignificantEntityParent {}
abstract class ParentClass {
protected abstract significantEntity: SignificantEntityParent;
public testMethod(): void {
console.log(this.significantEntity);
}
}
class TestClass1 extends ParentClass {
constructor() {
super();
// invalid!
this.significantEntity = new SignificantEntity1();
}
}
class TestClass2 extends ParentClass {
constructor() {
super();
// invalid!
this.significantEntity = new SignificantEntity2();
}
}
的漫游。
getSignificantEntity<SignificantEntity extends SignificantEntityParent>(): SignificantEntity
我遇到很多错误:
我不明白TypeScript试图告诉我什么。有没有有效的方法可以在抽象类中使用abstract class ParentClassA {
protected abstract getSignificantEntity<SignificantEntity extends SignificantEntityParent>(): SignificantEntity;
public logSignificantEntity(): void {
console.log(this.getSignificantEntity());
}
}
class TestClassA1 extends ParentClassA {
private significantEntity: SignificantEntity1;
constructor() {
super();
this.significantEntity = new SignificantEntity1();
}
protected getSignificantEntity(): SignificantEntity1 {
return this.significantEntity;
}
}
class TestClassA2 extends ParentClassA {
private significantEntity: SignificantEntity2;
constructor() {
super();
this.significantEntity = new SignificantEntity2();
}
protected getSignificantEntity(): SignificantEntity2 {
return this.significantEntity;
}
}
?
答案 0 :(得分:2)
它可能没有清晰的文档,但是abstract classes的抽象属性和方法必须在具体的子类中声明。他们不能只是被使用。这意味着您可以通过添加具体的属性声明来修正第一个示例:
class TestClass1 extends ParentClass {
significantEntity: SignificantEntity1; // declaration
constructor() {
super();
this.significantEntity = new SignificantEntity1();
}
}
class TestClass2 extends ParentClass {
significantEntity: SignificantEntity2; // declaration
constructor() {
super();
this.significantEntity = new SignificantEntity2();
}
}
当然,如果您在构造函数中所做的只是初始化一个属性,则可以删除该构造函数,并使用显式的property initializer,它既用作声明又用于初始化:
class TestClass1 extends ParentClass {
significantEntity = new SignificantEntity1();
}
class TestClass2 extends ParentClass {
significantEntity= new SignificantEntity2();
}
好的,希望能有所帮助。祝你好运!