How do I restore an object's prototype after retrieving from local storage using typescript?

前端 未结 1 828
心在旅途
心在旅途 2020-12-11 22:23

I have a typescript class with a getTotal() method on the prototype.

class Score {
    roundOne: any;
    roundTwo: any;
    roundThree: any;
    roundFour:          


        
相关标签:
1条回答
  • 2020-12-11 23:09

    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));
    
    0 讨论(0)
提交回复
热议问题