I have a class, for example:
class Team {
pointsFor: number;
pointsAgainst: number;
constructor(){
this.pointsFor = 0;
this.pointsAgainst = 0;
}
}
Now I would like to make a method for this class where I can update the property by key for example:
updateStats = (bool: boolean, property: string, increment: number) =>{
const key: keyof this = bool ? `${property}For` : `${property}Against`
this[key] += increment
}
However I get an error that string is not assignable to keyof this, and if I force the type like
const key: keyof this = bool ? `${property}For` as keyof this : `${property}Against` as keyof this
then I get an error: "Operator '+=' cannot be applied to types 'this[keyof this]' and 'number'."
Is there a way to accomplish what I want here where I call team.updateStats(true, 'points', 2) and update pointsFor?