【问题标题】:Why can't I do instanceof on a union?为什么我不能在联合上执行 instanceof?
【发布时间】:2015-05-12 13:38:48
【问题描述】:

在这种情况下它不允许 instanceof - 为什么?

public assign(color: string | ColorProperty | RgbProperty | RgbColor): void {
    super.assign(color);

    if (color instanceof ColorProperty) {

ps - 我喜欢工会!!!

【问题讨论】:

    标签: typescript1.4


    【解决方案1】:

    any 必须存在于联合中并不完全正确。这也有效。

    class Foo { } 
    class Bar { }
    
    var x: Foo | Bar = new Foo();
    if (x instanceof Foo) {
        // this is ok
    }
    

    但是,这不起作用,即使没有联合。

    var n: number = 123;
    if (n instanceof Foo) {
        // compile error
    }
    

    问题在编译器错误中说明。

    “instanceof”表达式的左侧必须是“any”类型、对象类型或类型参数。

    因此,当联合包含any 时,您总是可以将这些值视为any,这意味着没有编译时限制。否则,编译器只允许允许应用于任何单个类型的操作。

    【讨论】:

      【解决方案2】:

      似乎instanceof 关键字必须在联合中包含类型any 才能在函数中使用它。
      我的猜测是编译器需要处理所有类型保护返回 false 的情况 - 因此类型被推断为 any

      function assign(_color: any | string | ColorProperty | RbgProperty) {
          if (_color instanceof ColorProperty) {
          }
          // else may not be a string | ColorProperty | RbgProperty
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2010-10-08
        • 1970-01-01
        • 2014-05-15
        • 1970-01-01
        • 1970-01-01
        • 2012-07-06
        • 1970-01-01
        相关资源
        最近更新 更多