gpt4 book ai didi

typescript - 类中的抽象属性不能在构造函数中访问

转载 作者:行者123 更新时间:2023-12-03 16:51:33 24 4
gpt4 key购买 nike

在以下示例中,我收到 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com