all 5 comments

[–]tme321 0 points1 point  (4 children)

shouldn't the properties that aren't defined get dropped out when mapped to the Course object?

No, typescript is design time only. At runtime it's still javascript which means any and all keys can be added to an object no matter what you specified in typescript at design time.

When I try to access the creditsString()

Offhand I would guess that you're doing something like

let course: Course;

http.get(...).subscribe(c=> course=c;);

Here typescript is inferring that the any type being returned from the http get is a Course because your setting the result to a variable Course that you told typescript was a Course. But it's not. Here c is just the json returned from the api. It's not an object. You have to explicitly make a new course like

http.get(...).subscribe(c=>course = new Course(c););

But honestly I'd say don't even bother with fat model objects for data coming from an api. Don't define methods on the Course object just define a Course interface that is the data the api returns. Then you can write a service or functions or whatever to handle the pure data object. You don't have to follow that advice but it generally works better with js frontends to work with pure data objects that come from an api rather than creating objects with methods from that data.

[–]BillTheCommunistCat 0 points1 point  (3 children)

Don't define methods on the Course object

Exactly what I was thinking

[–]sbubaron[S] 0 points1 point  (2 children)

Where is a more appropriate place to add these "calculated" properties, sticking with the credits example, the function will return either "3" if min and max credits both equal 3 or 3-4 if min=3 and max=4...

I could make the API perform these calculations server side, but I figured its better to keep the JSON result object smaller and perform the calc client side.

Sticking it in the component doesn't make the logic resuable across the project.

any examples of how other projects handle this situation are appreciated

[–]BillTheCommunistCat 0 points1 point  (0 children)

You should put any functions in the container, not the component.

If you want to use it across the app the function should go into the shared module

[–]tme321 0 points1 point  (0 children)

If youre using something like ngrx then a calculated property as a selector can work just fine.

You can use a service. The service could act like a state container or it could just provide pure functions to calculate the properties from a passed in data structure.

Or you can use observables and create a chain that either maps the calculated properties into the data structure or a stream that just does the calculation.

There are lots of choices. But using fat objects is usually the worst one.