如何在不丢失TypeScript类属性的情况下将JSON对象列表转换为TypeScript对象列表?

时间:2015-11-06 23:57:26

标签: javascript typescript

我有这个Customer类:

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";
    }
}

在我的控制器中,我提取了一份客户名单:

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]);

如果有帮助,getAll()看起来像这样:

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

这句话让我感到悲伤:this.customers = response.data;

但是响应数据是强类型的,所以不应该&#34;知道&#34;关于客户和名称()?

当我这样做的时候,我当然会用愚蠢的JSON覆盖我的强类型数组,它没有我的name()方法。

那么如何在不复制列表中每个对象的每个属性的情况下保留我的名字方法呢?

这对我来说是不好的设计吗?拥有这些只读属性在C#中非常常见,但我对javascript世界有点新鲜。我应该使用实用程序类吗?

我目前的解决方法:

this.customers = response.data.map(customer => {
    return angular.copy(customer, new Customer());
});

构建一个全新数组并复制所有这些字段感觉不对(在我的真实项目中,Customer有更多属性)。

编辑:我发现了一些相关的SO问题,例如@xmojmr提到的Mapping JSON Objects to Javascript Objects。我的问题是特定于TypeScript的,我想知道TypeScript是否有自己的任何设施可以生成javascript以使其成为非问题。如果情况并非如此,并且我们确定TypeScript不能解决此类问题,那么我们可以将此问题视为重复。

1 个答案:

答案 0 :(得分:7)

你对发生的事情完全正确。键入typescript主要为您提供编译器检查。在幕后,所有内容都编译为JavaScript,而且不是强类型的。

所以,当你说:

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

你正在做的就是告诉编译器&#34;嘿,我非常确定我的api端点将返回Customer个对象的数组。&#34;但是正如你所知道的那样,它真的只会回归一个愚蠢的JSON&#34;阵列。

您可以考虑做的是创建一个描述API端点返回的JSON对象的接口。类似的东西:

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

然后getAll()成为:

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

然后你可以让一个类的构造函数将ICustomer作为参数。或者您可以使用静态方法创建一个类,该方法采用ICustomer并返回&#34; name&#34;。

显然,你现在正在做的事情是有效的,但我认为你正好寻找能够更好地传达意图的东西。

相关问题