Home > front end >  Error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'n
Error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'n

Time:01-01

I hope you can help me with this error.

Chrome explorer prints this trace:

error TS2362: The left-hand side of an arithmetic operation must be of type 'any', 'number', 'bigint' or an enum type.

39       <div ngSwitch="{{e%2}}">

It is my "app.component.html":

<mat-list role="list">
 <mat-list-item role="listitem" *ngFor="let e of lista; let i = index">
  {{i   1}}::{{e}} - 
  <div ngSwitch="{{e%2}}">
    <div *ngSwitchCase="0" [ngClass]="'impar'">impar</div>
    <div *ngSwitchCase="1" [ngClass]="'par'">par</div>
    <div *ngSwitchDefault="0">Sin resultados.</div>
  </div>
  <button mat-stroked-button color="accent" (click)="remover(i)">Remover</button>
  <mat-divider></mat-divider>
</mat-list-item>
</mat-list>

Additional info:

  • TS: "~4.5.2"
  • Angular CLI: 13.1.2
  • Node: 16.13.1
  • Package Manager: npm 8.1.2
  • OS: win32 x64

OBS: If I replace the modulus operator (%) by the plus ( ), it compiles satisfactory.

CodePudding user response:

Though the type of lista is not provided in the question, it seems to be of string[] type, maybe something like:

    lista = ['0', '1']

If that's the case, then you will get an error while trying to perform {{e%2} , as modulus operator cannot be used on string operand. Same would be the case for other operators like -, *.

Now why works is, because when used with string, it performs concatenation.

You can overcome the error by writing the interpolation as {{ e%2}}, provided it will always be a valid number within string, or else you will get NaN.

  • Related