0

I have a class which has multiple interfaces inside of it to model a JSON data. For example:

interface A {
   id: number;
}

interface B {
   name: string;
   surname?: string;
}

class MyClass implements A {
  people: B[];
  notes: string[];

  function1(){...}
  function2(){...}
}

And I have a JSON in the same structure:

{
  id: 1,
  people: [
    {
      name: "john"
    },
    {
      name: "alice",
      surname: "smith"
    }
  ],
  notes: [ "Very important top secret note" ]
}

Can I create an instance of MyClass from this JSON directly?

1 Answer 1

1

Your data structure is almost the same as your class, you'd have to add an id property to the class

class MyClass implements A {
    id: number;
    // ....
}

The problem is if you were trying to do something like this:

let data: MyClass = {
  id: 1,
  people: [
    {
      name: "john"
    },
    {
      name: "alice",
      surname: "smith"
    }
  ],
  notes: [ "Very important top secret note" ]
}

This won't work because your json does not have the methods (function1, function2).

One solution would be to really instantiate the MyClass and pass the json, or have a constructor method for that like

class MyClass {
    static createFrom(jsonData: A & B): MyClass {
       // create the objct and return
    }
}

Or, you could create a variable of that type by combining an existing instance of the class and spreading the json.

Like so:

let json = {
    id: 1,
    people: [
        {
            name: "john"
        },
        {
            name: "alice",
            surname: "smith"
        }
    ],
    notes: ["Very important top secret note"]
}
const c = new MyClass();

let mClass: MyClass = {...json, function1: c.function1, function2: c.function2 };

mClass.function1();

Link to playground

Sign up to request clarification or add additional context in comments.

1 Comment

First of all, A interface has the id field and MyClass implements it, should I declare it again? Secondly, I have much more interfaces/classes than this example, so initiating all of them with a constructor that takes json will take too much time. Lastly, I tried to create an instance of a class that have no methods as a: AClass = { ... } but when I did that, a instance of AClass returned false. Is the second method you suggested create a real instance of this class or is it just keeping it as json?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.