[英]Method that returns one of two types in Typescript
I have the following method that is supposed to return a component object if it's previously been registered 我有以下方法,如果它以前已经注册,它应该返回一个组件对象
/**
* 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];
}
Everything compiles and runs fine but my editor is throwing the following warning... 一切都编译并运行良好,但我的编辑抛出以下警告......
Property 'x' does not exist on type 'boolean | ComponentInterface'
when I try to run... 当我试图跑...
const oPositionComponent = oEntity.getComponent('position');
console.log(oPositionComponent.x);
Is there a better way of writing this so that my editor knows what I'm trying to achieve? 有没有更好的方法来编写这个,以便我的编辑知道我想要实现的目标?
Solution 解
Ok, so since I was actually checking the existence of the component in the previous step I just type-casted the return value... 好的,所以因为我实际上正在检查上一步中组件的存在,所以我只是输入了返回值...
aEntities = aEntities.filter((oEntity) => {
return oEntity.hasComponent('position');
});
aEntities.forEach((oEntity) => {
const oPositionComponent = <ComponentInterface> oEntity.getComponent('position');
this.context.translate(oPositionComponent.x, oPositionComponent.y);
});
Since it may return false
compiler assumes oPositionComponent.x may fail in this case. 由于它可能返回
false
假定oPositionComponent.x在这种情况下可能会失败。 You may assert the type (if you're sure you'd get the component and not false: 你可以断言类型(如果你确定你得到组件而不是假的:
console.log((<ComponentInterface>oPositionComponent).x);
But in production-quality code you should deal with possible false returns via type narrowing : 但在生产质量代码中,您应该通过类型缩小处理可能的错误返回:
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");
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.