Search code examples
reactjstypescript

How to typecase an object while also parsing a string within object?


I have a custom defined Model:

class Person {
    age: number;
    personality: Personality;
}

class Personality {
    shy: boolean;
    moody: boolean;
}

When I fetch result from API, I receive:

{
    age: 20;
    personality: "\{\"shy\": \"true\",\"moody\":\"false\"\}"
}

I assign API response to a variable using:

response.body().personality = JSON.parse(response.body().personality)
const person = response.body() as Person

Here personality is string which I need to be parsed directly.

How can I avoid this statement : response.body().personality = JSON.parse(response.body().personality)


Solution

  • You can create a constructor in your Person class that will handle the parsing of the personality field. This way, whenever you create a new Person object, the personality field will be automatically parsed from a string to a Personality object.

    class Personality {
        shy: boolean;
        moody: boolean;
    
        constructor(data: any) {
            this.shy = data.shy === 'true';
            this.moody = data.moody === 'true';
        }
    }
    
    class Person {
        age: number;
        personality: Personality;
    
        constructor(data: any) {
            this.age = data.age;
            this.personality = new Personality(JSON.parse(data.personality));
        }
    }
    

    Now, when you receive the response from the API, you can create a new Person object like this:

    const person = new Person(response.body());
    

    This will automatically parse the personality field from a string to a Personality object.