4

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.

1

1 Answer 1

7

You're exactly right about what is happening. Typing in typescript mainly provides you with compiler checking. Under the covers, everything compiles to JavaScript which isn't strongly typed.

So, when you say:

getAll(): ng.IHttpPromise<Array<Customer>> {
    return this.http.get("/api/customers");
}

all you are really doing is telling is telling the compiler "Hey, I'm pretty sure my api endpoint is going to return an array of Customer objects." But as you know, it really just returns a "dumb JSON" array.

What you could consider doing, is creating an interface that describes the JSON object being returned by the API endpoint. Something like:

interface ICustomer {
    id: number;
    company: string;
    firstName: string;
    lastName: string;
}

And then getAll() becomes:

getAll(): ng.IHttpPromise<Array<ICustomer>> {
    return this.http.get("/api/customers");
}

Then you could have a class who's constructor takes ICustomer as a parameter. Or you could create a class with a static method that takes ICustomer and returns the "name".

Obviously, what you are doing now works, but I think you're right to be looking for something that better communicates the intent.

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

3 Comments

Does TypeScript have a feature for this? For example, maybe I don't tell TypeScript that my API returns a Customer, and instead tell it to cast the results into a Customer List, could it then solve this problem for me? If that's not the kind of thing TypeScript can/should do, then I'm satisfied with your answer, or just calling my question a duplicate.
Unfortunately, TypeScript does not allow you to use type casting to actually change the structure of an object. It is all about using types to provide compiler checking for errors.
On the other hand, using types can really improve the readability, and maintainability of the code. By choosing good class names, you can make an otherwise complex object transformation clear.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.