返回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);
});
weirdan

由于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] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

返回两种类型之一的对象

如何指示(TypeScript)参数类型必须恰好是两种类型之一(而不是联合)?

接受两种类型之一的泛型类

包含词性的两种类型句子中的随机选择之一

变量(枚举?)在Swift 2中持有两种类型之一

在TypeScript中,对象返回两种类型的并集,但会生成错误

在打字稿中返回两种类型的函数

如何在 Typescript 中实现两种类型的比较

c函数返回两种可能的类型之一

Scala:是否可以将类型参数强制为两种类型之一?

如何用可能具有两种类型的角类型之一的变量创建类

打字稿:两种类型之一不适用于接口密钥

如何使结构接受两种类型之一作为参数?

如何将函数参数定义为两种类型之一

XSD Schema 元素可以是两种类型之一

如何将回调定义为两种类型之一?

具有可以是两种类型之一的数据成员的类

用一种类型参数化的方法接受两种类型

提取两种类型使用的方法

比较Dart中的两种类型

当参数可能是两种类型之一时如何声明(和传递)Julia 函数参数

返回从同一抽象类派生的两种类型

如何在 TypeScript 中将两种类型绑定在一起?

在Typescript中将两种类型完美地组合成一个界面

Typescript 函数参数有两种类型,一种类型的属性无法访问,因为它不是另一种类型的属性

自动检测两种返回类型之一

Ajax 可以成功() 处理两种类型的返回吗?

TypeScript:接口不能同时扩展两种类型

在类型列表中交换两种类型