在下面的示例中,我将获得TypeScript error Abstract property 'name' in class 'Minigame' cannot be accessed in the constructor.
我正在努力思考如何才能实现这一点。我不能将具体类的名称传递给super()调用,因为在调用之前我不能访问对象的属性,而且我不能将属性设为static,因为抽象类不能强制这样做。
应该如何组织,以确保每个名称都实例化一个Explanation对象,该对象需要具体类的Minigame属性?让名称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();
}
}发布于 2019-06-27 18:43:22
它对于字符串来说有点难看,但是你可以这样做:
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();
}
}https://stackoverflow.com/questions/54273218
复制相似问题