I have a typescript class with a getTotal() method on the prototype.
class Score {
roundOne: any;
roundTwo: any;
roundThree: any;
roundFour:
Parsing a json doesn't result in instance of classes but with simple js objects which contain the same properties.
You have (at least) two ways to solve this:
(1) Add a constructor which can handle this state object:
class Score {
roundOne: any;
roundTwo: any;
...
constructor(state: Score) {
this.roundOne = state.roundOne;
this.roundTwo = state.roundTwo;
...
}
getTotal() {
...
}
}
let scores = (JSON.parse(localStorage.getItem('scores')) as Score[])
.map(score => new Score(score));
Notice that even though I use the type Score
for the state objects it's not really the case, they just share the same structure (minus the method). You can make an interface for that as well:
interface State {
roundOne: any;
roundTwo: any;
...
}
(2) Use Object.assign:
let scores = (JSON.parse(localStorage.getItem('scores')) as Score[])
.map(score => Object.assign(new Score(), score));