繁体   English   中英

无法访问联合类型(TypeScript)中的参数

[英]Unable to access parameters from union types (TypeScript)

为什么无法访问像这样的联合类型中的属性:

export interface ICondition {
  field: string
  operator: string
  value: string
}

export interface IConditionGroup {
  conditions: ICondition[]
  group_operator: string
}

function foo(item: ICondition | IConditionGroup) {
  if(typeof item.conditions === "undefined") { // does not work
    let field = item.field; // does not work
    ///.. do something 
  } else {
    let conditions = item.conditions; // does not work
    /// .. do something else
  }
}

我得到这些错误:

error TS2339: Property 'conditions' does not exist on type 'ICondition | IConditionGroup'.
error TS2339: Property 'conditions' does not exist on type 'ICondition | IConditionGroup'.
error TS2339: Property 'field' does not exist on type 'ICondition | IConditionGroup'.

但是我必须强制转换类型才能使其正常工作-像这样:

function foo2(inputItem: ICondition | IConditionGroup) {
  if(typeof (<IConditionGroup>inputItem).conditions === "undefined") {
    let item= (<ICondition>inputItem);
    let field = item.field;
    ///.. do something 
  } else {
    let item= (<IConditionGroup>inputItem);
    let conditions = item.conditions;
    /// .. do something else
  }
}

我知道类型信息在JS中丢失了,为什么我必须在TS中显式转换它?

Typescript使用Type Guards处理此问题,通常很简单:

if (typeof item === "string") { ... } else { ... }

要么

if (item instanceof MyClass) { ... } else { ... }

但是对于您来说,由于您无法使用接口,因此您需要创建自己的用户定义类型保护

function isConditionGroup(item: ICondition | IConditionGroup): item is IConditionGroup {
    return (item as IConditionGroup).conditions !== undefined;
}

function foo(item: ICondition | IConditionGroup) {
    if (isConditionGroup(item)) {
        let conditions = item.conditions;
        // do something
    } else {
        let field = item.field;
        // do something else
    }
}

操场上的代码

您也可以在没有类型保护的情况下执行此操作:

function foo(item: ICondition | IConditionGroup) {
    if ((item as IConditionGroup).conditions !== undefined) {
        let conditions = (item as IConditionGroup).conditions;
        // do something
    } else {
        let field = (item as ICondition).field;
        // do something else
    }
}

但这是冗长的方式,因为您需要输入3次而不是一次的断言item

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM