【发布时间】:2021-03-02 20:35:21
【问题描述】:
我正在 TypeScript 中开发一个实体组件系统,其中实体包含其组件的映射。 CT 代表ComponentType 这是代码:
class Entity {
components: Map<CT, Component>;
constructor() {
this.components = new Map();
}
get(componentType: CT): Component {
return this.components.get(componentType);
}
}
const enum CT {
Position,
Health // etc..
}
class Component {
type: CT;
constructor(type: CT) {
this.type = type;
}
}
class HealthComponent extends Component {
amount: number;
constructor() {
super(CT.Health);
this.amount = 0;
}
}
问题是当我做类似的事情时:
let healthComponent = new HealthComponent();
healthComponent.amount = 100;
let entity = new Entity();
entity.components.set(healthComponent.type, healthComponent);
let position = entity.get(CT.Health);
console.log(health.amount);
我收到此错误:Property 'amount' does not exist on type 'Component'
如果我将Entity.get 函数更改为像这样返回any,那么错误就会消失:
get(componentType: CT): any {
return this.components.get(componentType);
}
但是我不再得到我想要的代码完成。
是否可以让它返回正确的类型,以便我可以进行代码完成和错误检测?
【问题讨论】:
-
PositionComponent在哪里使用? -
@Vishnudev 好点 - 刚刚将其添加到示例中以进行澄清
-
你能
if (position is PositionComponent) console.log((position as PositionComponent).x)吗? -
@DM 我想尽可能避免这种情况,因为我已经知道类型。
-
你知道类型,但你的编译器不知道。
Map只包含没有x属性的Components。您也许可以尝试Map<CT, Component | PositionComponent>,但我怀疑这是正确的 TS 方法。
标签: javascript typescript generics subclass