我有以下方法,如果以前已经注册过,则应该返回一个组件对象
/**
* Retrieve a component
* @param string sComponentName The name of the component to look for
* @return ComponentInterface | boolean
*/
public getComponent(sComponentName: string): boolean | ComponentInterface {
if(!this.hasComponent(sComponentName)) {
return false;
}
return this.components[sComponentName];
}
一切都能编译并正常运行,但是我的编辑器抛出以下警告...
Property 'x' does not exist on type 'boolean | ComponentInterface'
当我尝试跑步...
const oPositionComponent = oEntity.getComponent('position');
console.log(oPositionComponent.x);
有没有更好的编写方法,以便我的编辑知道我要实现的目标?
解
好的,因为在上一步中实际上是在检查组件的存在,所以我只键入了返回值...
aEntities = aEntities.filter((oEntity) => {
return oEntity.hasComponent('position');
});
aEntities.forEach((oEntity) => {
const oPositionComponent = <ComponentInterface> oEntity.getComponent('position');
this.context.translate(oPositionComponent.x, oPositionComponent.y);
});
由于false
编译器可能会返回oPositionComponent.x,因此在这种情况下可能会失败。您可以断言类型(如果您确定会得到组件,而不是false:
console.log((<ComponentInterface>oPositionComponent).x);
但是在生产质量的代码中,您应该通过缩小类型来处理可能的错误返回:
if (oPositionComponent instanceof ComponentInterface) { // this will only work with classes, not interfaces (?)
console.log(oPositionComponent.x);
} else { // this must be false
console.log("component is not registered");
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句