0

I am trying to cast a JSON object like the following example:

class Person {
    constructor(
      public firstName, 
      public lastName
   ) {}

   function getName() {
      return this.firstName + “ “ + this.lastName;
   }
}

The goal is to parse the JSON which looks like this:

    {
    firstName: “Max“,
    lastName: “Mustermann“
    }

to an instance of the above class to access all properties and methods.

Is there an easy way to create a function which can make such a functionality possible for such type of JSONs/classes? Also nested objects should be possible.

I can write a factory method for every different class but there should be an better way to get such functionality.

1
  • "I can write a factory method for every different class but there should be an better way to get such functionality." - actually no, writing a factory method per class is the only proper solution. This is necessary to deal with different constructor arguments and internal state - even if the class does not yet have these, it might get them later, you should always simply call the factory method. Commented May 29, 2023 at 12:21

1 Answer 1

1

Use Object.assign

Create your class like this, observe the constructor

class Person {
       public firstName: string; 
       public lastName: string;

       public constructor(init?: Partial<Person>) {
        Object.assign(this, init);
       }

      function getName() {
        return this.firstName + “ “ + this.lastName;
      }
   }
  

Pass the json into this constructor

let person =  new Person({firstName: "A", lastName: "B" });
console.log(person);
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.