我有使用类型脚本,并且有两个接口,接口1或接口2,例如:

export interface Interface1 {
  propA: string;
  propB: string;
}

export interface Interface12 {
  propA: string;
  propC: string;
}

以及返回实现可能接口之一的对象的方法,如下所示:

doSomething: (state): Interface1 | Interface2 | null => {
      if (state === 1) {
        return ObjectImplementingInterface1;
      }
      if (state === 2) {
        return ObjectImplementingInterface2;
      }
      return null;
    }

然后,我想使用该方法的结果并使用只存在于Interface2中的属性,例如:

const varExample = this.doSomething(this.s);
      if (varExample) {
        if ('type' in varExample && varExample.type === 'Interface1') {
          this.importantResult = varExample.propA;
        }

        if ('type' in varExample && varExample.type === 'Interface2') {
          this.importantResult = varExample.propC;
        }
      } else {
        this.importantResult = 'someValue';
      }

编译器不允许我使用proC,并抛出以下错误:

Property 'propC' does not exist on type '(Interface1 | Interface2) & Record<"type", unknown>'.
Property 'propC' does not exist on type 'Interface1 & Record<"type", unknown>'.

我怎样才能强迫TypeScrip知道这个对象一定是实现Interface2的对象呢?

推荐答案

您可以通过使用所谓的类型断言或类型转换来强制TypeScrip使用特定的接口或类型. 我们通常使用的方法是使用关键字as.

this.importantResult = (varExample as Interface2).propC;

Javascript相关问答推荐

如何将元素排列得彼此靠近?

使用脚本标签时的JSDoc智能感知

获取POS餐厅会话用户/收银员

详细更改参考价值:"

错误:找不到react-redux上下文值;请确保该组件包装在React原生Expo应用程序中的提供者中

使用CDO时如何将Vue组件存储在html之外?

使用typeof运算符获取对象值类型-接收字符串而不是数组

序列查找器功能应用默认值而不是读取响应

根据总价格对航班优惠数组进行排序并检索前五个结果- Angular HTTP请求

是否有方法在OpenWeatherMap API中获取过go 的降水数据?

通过在页面上滚动来移动滚动条

我可以使用CSS有效地实现最大宽度=100%和最大高度=100%,而无需父母有明确的/固定的宽度和高度,替代方法吗?

扫描qr code后出错whatter—web.js

自定义高图中的x轴标签序列

如何调用名称在字符串中的实例方法?

是否可以在Photoshop CC中zoom 路径项?

无法检索与Puppeteer的蒸汽游戏的Bundle 包价格

Next.js无法从外部本地主机获取图像

Clip-Path在网页浏览器(Mozilla、Edge、Chrome)上不能正常工作,但在预览版Visual Code Studio HTML、CSS、JS上却能很好地工作

本地损坏的Java脚本