Why I get error when I try to declare local variable?

Michael

I bew to the typescript. In my function in the component I try to declare a local variable "contains":

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

    //some logic
    
    }

but on this row:

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

on the Boolean I get this error:

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

Why I get an error on the variable declaration?

CertainPerformance

The Boolean type is something that you'd get if you invoked the Boolean constructor:

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

This is almost never what you want - it can behave quite oddly. For example, a Boolean object containing false is truthy. Its typeof is also object, not boolean. Use the boolean type instead.

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

Or, even better, leave out the type annotation entirely, and let TS infer it automatically:

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

That's usually preferable, since it leads to less boilerplate and less code that needs to be read.

Collected from the Internet

Please contact [email protected] to delete if infringement.

edited at
0

Comments

0 comments
Login to comment

Related