Home > Mobile >  An arithmetic operand must be of type 'any', 'number', 'bigint' or an
An arithmetic operand must be of type 'any', 'number', 'bigint' or an

Time:06-03

I'm trying to create a class with generics to count votes, but typescript still throwing this error "An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type.ts(2356)"

const votos1 = {
  JavaScript: 0,
  Typescript: 0,
  Python: 0,
};

class Votes<T> {
  constructor(private _votos: { [k: string | number]: T } = {}) {}

  checkEmpty(): boolean {
    return Object.keys(this._votos).length === 0;
  }

  showVotes(): void {
    for (const opcao in this._votos) {
      console.log(opcao   ' '   this._votos[opcao]);
    }
  }

  vote(voteOption: string): void {
    if (voteOption) {
      this._votos[voteOption]  ; //An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type.ts(2356)
    } else {
      console.log('Digite a opção de voto desejada!');
    }
  }
}

export const votacao1: Votes<number> = new Votes(votos1);
console.log(votacao1.showVotes());


I also tried this:

vote(voteOption: string): void {
    Object.entries(this._votos).forEach(([key, value]) => {
      console.log(typeof value); //returns number in all cases

      if (key === voteOption && typeof value === 'number') {
        this._votos[key]  ; //An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type.ts(2356)
      }
    });
  }

I also tried to convert to number and create typeguards but got the same error, someone knows how to fix it ?

CodePudding user response:

Since you expect that property value should be always number it doesn't need to be generic (since it is known).

I think that what you are trying to accomplish here is generic constrained type of _votos. Eg:

const votos1 = {
  JavaScript: 0,
  Typescript: 0,
  Python: 0,
};

class Votes<T extends Record<string, number>> {
  constructor(private _votos: T) {}

  checkEmpty(): boolean {
    return Object.keys(this._votos).length === 0;
  }

  showVotes(): void {
    for (const opcao in this._votos) {
      console.log(opcao   ' '   this._votos[opcao]);
    }
  }

  vote(voteOption: keyof T): void {
    if (voteOption) {
      this._votos[voteOption]  ;
    } else {
      console.log('Digite a opção de voto desejada!');
    }
  }
}

export const votacao1: Votes<typeof votos1> = new Votes(votos1);
console.log(votacao1.showVotes());

console.log(votacao1.vote("Typescript"));

// since argument of this methiod is keyof T you can pass only valid key here
console.log(votacao1.vote("wrong"));
  • Related