[英]Method that returns one of two types in Typescript
我有以下方法,如果它以前已經注冊,它應該返回一個組件對象
/**
* 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在這種情況下可能會失敗。 你可以斷言類型(如果你確定你得到組件而不是假的:
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");
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.