2

I have a TypeScript class in angular looking like this:

import {HotelModel} from './hotel.model';
import {LocationModel} from './location.model';

export class CountryModel {
  id: number;
  name: string;
  description: string;
  countryFlagImagePath: string;
  themeFotoImagePath: string;
  hotels: HotelModel[];
  locations: LocationModel[];
  constructor(values: Object = {}) {
    Object.assign(this, values);
  }
}

I retrieve data from API, where the model object are similiar to these ones. The assign in the constructor works fine until I reach the nested model properties.

For example array of HotelModel. Then It just assigns the data to array of plain objects instead of array of HotelModel.

Is there any easy way (similiar to the object assign where I do not need to care about assigning every simple class member) for the nested properties? (If possible for properties nested X times)?

3
  • 2
    You should probably use interfaces instead of classes, unless you actually have logic inside of your types. Commented Aug 12, 2018 at 12:35
  • Well, this is just a beg of application. There will be some logic later. Commented Aug 12, 2018 at 13:05
  • If the data comes from an external source (i.e. through JSON data), then you’re better off creating a separate service that works with the data though. It is somewhat unusual to have typed business objects with logic in JavaScript. Commented Aug 12, 2018 at 13:06

2 Answers 2

1

The most straightforward way is to take advantage of one of the common typescript JSON object mapper library

If you use it as a keyword searching on NPM, you'll find a few of them. Most of those libraries achieve the mapping feature by using typescript property decorators to define how to map those properties from plain object/JSON to newly instantiated JavaScript/TypeScript class object.

I think this is exactly what you needed. However, I have to say from your code example I don't see the real benefit of doing this. Most of the time you don't need to have a real class object unless the object is involved in some sort of business logic with its own class methods. And this is usually not the best practice when the class is a direct map from endpoint response.

So I would suggest, in your scenario, use interface instead of class, and don't bother with mapping them.

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

Comments

0

Is there any easy way - no, you shall track the occurrence and remap it

Builder or factory method patterns are good for the case

Comments

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.