I have this Customer class:
export class Customer {
id: number;
company: string;
firstName: string;
lastName: string;
name(): string {
if (this.company)
return this.company;
if (this.lastName && this.firstName)
return this.lastName + ", " + this.firstName;
if (this.lastName)
return this.lastName;
if (this.firstName)
return this.firstName;
if (this.id > 0)
return "#" + this.id;
return "New Customer";
}
}
In my controller I pull down a list of customers:
export class CustomersController {
static $inject = ["customerService", "workflowService"];
ready: boolean;
customers: Array<Customer>;
constructor(customerService: CustomerService, workflowService: WorkflowService) {
customerService.getAll().then(
(response) => {
this.customers = response.data;
this.ready = true;
},
() => {
this.ready = true;
}
);
workflowService.uiCustomer.reset();
}
}
angular.module("app")
.controller("CustomersController", ["customerService", "workflowService", CustomersController]);
If it helps, getAll() looks like this:
getAll(): ng.IHttpPromise<Array<Customer>> {
return this.http.get("/api/customers");
}
It's this statement that's causing me grief: this.customers = response.data;
But response.data is strongly typed, so shouldn't it "know" about Customer and name()?
When I do that, of course I am overwriting my strongly typed array with the dumb JSON one, which doesn't have my name() method on it.
So how do I keep my name method without copying every property of every object in the list?
Is this bad design on my part? Having these read-only properties was really common in C#, but I'm a little new to the javascript world. Should I be using a utility class instead?
My current work-around:
this.customers = response.data.map(customer => {
return angular.copy(customer, new Customer());
});
Feels wrong to build a whole new array and copy all those fields (in my real project Customer has many more properties).
Edit: I've found a few related SO questions, such as Mapping JSON Objects to Javascript Objects as mentioned by @xmojmr. My question was specific to TypeScript and I was wondering if TypeScript had any facilities of its own that would generate the javascript to make this a non-issue. If that's not the case, and we're sure TypeScript doesn't aim to solve this class of problem, then we can regard this question as a duplicate.