Emis
Emis

Reputation: 602

Parse JSON to TypeScript object

Let say I have a Object:

class Person{
id: number;
name: string;
}

And Json from API:

{
"id": "10",
"name": "Person Name",
"email": "[email protected]"
}

How to convert from JSON to Person object, excatly variables that is in Person class?

I tried this:

Object.assign(Person.prototype, this.jsonList))

but i'ts not working

Upvotes: 0

Views: 730

Answers (1)

user663031
user663031

Reputation:

The information about what properties are declared in a class is "metadata", and is not directly accessible. Hence, there is no straightforward way to copy only those properties present in a class from some input which might contain additional unwanted properties, other than explicitly enumerating them.

The feature of JavaScript/TypeScript which does have access to such metadata is decorators. Therefore, to solve your problem in a generalized way requires such a decorator. The decorator could generate a static method which copied just those properties which actually exist on the class. That would look like that:

@ConstructFromJsonWithExtraGarbage()
class Person {
}

const sally = Person.constructWithExtraGarbage(
  {id: 1, name: "Sally", email: "[email protected]"});

Actually writing this decorator is beyond the scope of this answer.

Upvotes: 1

Related Questions