算术操作数必须是 'any'、'number'、'bigint' 类型或枚举类型 type.ts(2356)

An arithmetic operand must be of type 'any', 'number', 'bigint' or an enum type.ts(2356)

我正在尝试用泛型创建一个 class 来计算选票,但打字稿仍然抛出这个错误 “算术操作数必须是 'any'、'number'、'bigint' 类型或枚举类型 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());


我也试过这个:

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)
      }
    });
  }

我也尝试过转换为数字并创建类型保护,但遇到了同样的错误,有人知道如何解决吗?

因为您希望 属性 值应该始终是数字,所以它不需要是通用的(因为它是已知的)。

我认为你在这里试图完成的是 _votos 的泛型约束类型。例如:

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"));