1

I am building a sample project with Angular2/Typescript in order to use it as a new frontend for an existing backend code.

I really like the ability to create types and consider to use some of the JSON objects served by the backend as typed classes like this:

module DomainObjects {
  export class SomeDomainObject {
    constructor(attr1:string, attr2:number) {...}
    ...
  }
}

Some of the JSON code that is returned by the backend is very large, so I don't want to work with a huge amount of parameters in the constructor. At best i just pass a JSON object as a single parameter to the constructor which does some checks (or not). On the other hand I'd like to access the JSON object directly. Is something like this possible:

myobject:SomeDomainObject;
...
this.myobject = new SomeDomainObject({id:10,color:'green'});

and access myobject in a template like this

{{myobject.color}}

without having another reference like {{myobject.json.color}}

1 Answer 1

1

You can model your JSON data with interfaces (instead of classes). Then you can simply assign the received JSON to it (instead of calling a constructor).

For validation you will most likely need to build a validation function that checks if the received JSONs structure really equals the type that you described in your interface. You could also build a validate and assign function with a signature like

function toTypedData(input: any):SomeDomainObject { ... }

You can also use JSON schema and a suitable validation library to perform that step.

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

2 Comments

Thank you. I think that pretty much solves the issue. Coming from the Java world, I had a slightly different notion of what interfaces are for.
@user3802631 The only single issue with using interfaces is that if your JSON represents objects that have methods (eg.: if your SomeDomainObject had a method), those methods won't exist on objects you think they exist.

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.