繁体   English   中英

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

[英]How do I cast a list of JSON objects into a list of TypeScript objects without losing properties on the TypeScript class?

我有这个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;

但是response.data是强类型的,所以它不应该“知道”关于Customer和name()吗?

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

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

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

我目前的解决方法:

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

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

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

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

所以,当你说:

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

所有你真正在做的就是告诉编译器“嘿,我很确定我的api端点将返回一个Customer对象数组。” 但是如你所知,它实际上只返回一个“哑的JSON”数组。

您可以考虑做的是创建一个描述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并返回“name”。

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM