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

为什么我在声明局部变量时出错?

  •  0
  • Michael  · 技术社区  · 4 年前

    我看打字稿。

      setUpgrade($event) {
        
         contains : Boolean = this.selectedUpgrades.includes($event);
    
        //some logic
        
        }
    

    但在这一排:

     contains : Boolean = this.selectedUpgrades.includes($event);   
    

    在布尔值上我得到了这个错误:

      Type 'boolean' is not assignable to type 'BooleanConstructor'.
      
    

    为什么变量声明出错?

    1 回复  |  直到 4 年前
        1
  •  2
  •   CertainPerformance    4 年前

    这个 Boolean 类型是调用布尔构造函数时会得到的:

    const somethingWeird = new Boolean(Math.random() < 0.5);
    

    false 是真的。它 typeof 也是 object boolean . 使用 布尔型

    const contains : boolean = this.selectedUpgrades.includes($event);
    

    或者,更好的方法是完全忽略类型注释,让TS自动推断:

    const contains = this.selectedUpgrades.includes($event);
    

    这通常更可取,因为这样可以减少样板文件和需要读取的代码。