Javascript 如何将JSON对象列表强制转换为TypeScript对象列表,而不丢失TypeScript类的属性?
我有这个客户类别:Javascript 如何将JSON对象列表强制转换为TypeScript对象列表,而不丢失TypeScript类的属性?,javascript,typescript,Javascript,Typescript,我有这个客户类别: export class Customer { id: number; company: string; firstName: string; lastName: string; name(): string { if (this.company) return this.company; if (this.lastName && this.firstName)
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]);
构建一个全新的阵列并复制所有这些字段(在我真正的项目中,客户有更多的属性),这是不对的
编辑:我发现了一些相关的SO问题,比如@xmojmr提到的。我的问题是针对TypeScript的,我想知道TypeScript是否有自己的功能来生成javascript,使之成为一个非问题。如果情况并非如此,并且我们确信TypeScript的目的不是解决这类问题,那么我们可以将此问题视为重复问题。您对发生的事情的看法完全正确。键入typescript主要为您提供编译器检查。在封面下,所有东西都编译成非强类型的JavaScript 所以,当你说:
getAll(): ng.IHttpPromise<Array<Customer>> {
return this.http.get("/api/customers");
}
然后getAll()
变成:
getAll(): ng.IHttpPromise<Array<ICustomer>> {
return this.http.get("/api/customers");
}
getAll():ng.ihttpromise{
返回此.http.get(“/api/customers”);
}
然后,您可以让一个类的构造函数将iccustomer
作为参数。或者,您可以使用静态方法创建一个类,该方法接受iccustomer
,并返回“name”
显然,您现在所做的工作是有效的,但我认为您正在寻找能够更好地传达意图的东西是正确的。TypeScript是否有此功能?例如,也许我没有告诉TypeScript我的API返回了一个客户,而是告诉它将结果转换到客户列表中,然后它能帮我解决这个问题吗?如果TypeScript不能/不应该这样做,那么我对你的回答很满意,或者只是把我的问题称为重复问题。不幸的是,TypeScript不允许你使用类型转换来实际更改对象的结构。所有这些都是关于使用类型来提供编译器错误检查。另一方面,使用类型可以真正提高代码的可读性和可维护性。通过选择好的类名,您可以使原本复杂的对象转换变得清晰。
getAll(): ng.IHttpPromise<Array<Customer>> {
return this.http.get("/api/customers");
}
interface ICustomer {
id: number;
company: string;
firstName: string;
lastName: string;
}
getAll(): ng.IHttpPromise<Array<ICustomer>> {
return this.http.get("/api/customers");
}