在以下示例中,我收到 TypeScript 错误 Abstract property 'name' in class 'Minigame' cannot be accessed in the constructor.
我正在努力思考如何实现这一点。我无法将具体类的名称传递给 super()
调用,因为在调用之前我无法访问对象的属性,并且我无法创建属性 static
因为抽象类不能强制执行。
这应该如何组织以保证每个Minigame
实例化 Explanation
对象,它需要具体类的名称属性?正名static
(并删除抽象要求)真的是保持简单的最佳选择吗?
abstract class Minigame {
abstract name: string;
explanation: Explanation;
constructor() {
this.explanation = new Explanation(this.name);
}
}
class SomeGame extends Minigame {
name = "Some Game's Name";
constructor() {
super();
}
}
最佳答案
字符串有点难看,但你可以这样做:
abstract class Minigame {
abstract GetName(): string;
explanation: Explanation;
constructor() {
this.explanation = new Explanation(this.GetName());
}
}
class SomeGame extends Minigame {
GetName(): string {
return "Some Game's Name";
}
constructor() {
super();
}
}
关于typescript - 类中的抽象属性不能在构造函数中访问,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/54273218/