代码之家  ›  专栏  ›  技术社区  ›  John

在函数参数中使用带角度的union类型时出现编译错误

  •  1
  • John  · 技术社区  · 8 年前

    根据 https://www.typescriptlang.org/docs/handbook/declaration-files/do-s-and-don-ts.html ,您应该能够对函数中的参数使用多种类型(请参见联合部分)

    /* OK */
    interface Moment {
        utcOffset(): number;
        utcOffset(b: number|string): Moment;
    }
    

    然而,我对以下方法的角度报告未解决变量存在问题:

    isFooBar(fooBar: Foo|Bar){
       if(fooBar.isFoo){ // error here
           console.log("is foo");
       }
    }
    

    我有两个类定义:

    export class Foo {
      isFoo: boolean;
    }
    
    export class Bar {
      isBar: boolean;
    }
    

    我用错了吗?

    看见 StackBlitz

    1 回复  |  直到 8 年前
        1
  •  2
  •   Titian Cernicova-Dragomir    8 年前

    由于该参数是一个联合,因此您只能访问这两种类型的公共成员。自从 isFoo 两者都不存在,将无法访问。对于这个用例,您可以使用 in 键入guard以检查属性是否存在。

    export class Foo {
        isFoo: boolean;
    }
    
    export class Bar {
        isBar: boolean;
    }
    
    function isFooBar(fooBar: Foo | Bar) {
        if ('isFoo' in fooBar) {
            // fooBar is of type Foo here
            console.log("is foo " + fooBar.isFoo);
        } else {
            // fooBar is of type Bar here
            console.log("is bar " + fooBar.isBar);
        }
    }
    
    推荐文章