我目前正在尝试将收到的JSON对象转换为具有相同属性的TypeScript类,但无法使其正常工作。我究竟做错了什么?
员工阶层
export class Employee{ firstname: string; lastname: string; birthdate: Date; maxWorkHours: number; department: string; permissions: string; typeOfEmployee: string; note: string; lastUpdate: Date; }
员工字符串
{ "department": "<anystring>", "typeOfEmployee": "<anystring>", "firstname": "<anystring>", "lastname": "<anystring>", "birthdate": "<anydate>", "maxWorkHours": <anynumber>, "username": "<anystring>", "permissions": "<anystring>", "lastUpdate": "<anydate>" //I will add note later }
我的尝试
let e: Employee = new Employee(); Object.assign(e, { "department": "<anystring>", "typeOfEmployee": "<anystring>", "firstname": "<anystring>", "lastname": "<anystring>", "birthdate": "<anydate>", "maxWorkHours": 3, "username": "<anystring>", "permissions": "<anystring>", "lastUpdate": "<anydate>" }); console.log(e);
链接到打字稿游乐场
编译器允许您将返回的对象强制JSON.parse转换为类的原因是因为typescript基于结构子类型。 您实际上并没有的实例Employee,而是拥有一个具有相同属性的对象(如在控制台中看到的)。
JSON.parse
Employee
一个简单的例子:
class A { constructor(public str: string, public num: number) {} } function logA(a: A) { console.log(`A instance with str: "${ a.str }" and num: ${ a.num }`); } let a1 = { str: "string", num: 0, boo: true }; let a2 = new A("stirng", 0); logA(a1); // no errors logA(a2);
(操场上的代码)
没有错误是因为a1满足类型,A因为它具有所有属性,并且只要它具有相同的属性,logA即使函数接收的实例不是该函数的实例,也可以在没有运行时错误的情况下调用该函数A。
a1
A
logA
当您的类是简单的数据对象并且没有方法时,这很好用,但是一旦您引入了方法,事情就会崩溃:
class A { constructor(public str: string, public num: number) { } multiplyBy(x: number): number { return this.num * x; } } // this won't compile: let a1 = { str: "string", num: 0, boo: true } as A; // Error: Type '{ str: string; num: number; boo: boolean; }' cannot be converted to type 'A' // but this will: let a2 = { str: "string", num: 0 } as A; // and then you get a runtime error: a2.multiplyBy(4); // Error: Uncaught TypeError: a2.multiplyBy is not a function
这很好用:
const employeeString = '{"department":"<anystring>","typeOfEmployee":"<anystring>","firstname":"<anystring>","lastname":"<anystring>","birthdate":"<anydate>","maxWorkHours":0,"username":"<anystring>","permissions":"<anystring>","lastUpdate":"<anydate>"}'; let employee1 = JSON.parse(employeeString); console.log(employee1);
如果您尝试JSON.parse在不是字符串的对象上使用它:
let e = { "department": "<anystring>", "typeOfEmployee": "<anystring>", "firstname": "<anystring>", "lastname": "<anystring>", "birthdate": "<anydate>", "maxWorkHours": 3, "username": "<anystring>", "permissions": "<anystring>", "lastUpdate": "<anydate>" } let employee2 = JSON.parse(e);
然后,您将收到错误消息,因为它不是字符串,而是对象,如果您已经以这种形式使用它,则无需使用JSON.parse。
但是,正如我所写的那样,如果您采用这种方式,那么您将没有类的实例,只有一个具有与类成员相同属性的对象。
如果您想要一个实例,那么:
let e = new Employee(); Object.assign(e, { "department": "<anystring>", "typeOfEmployee": "<anystring>", "firstname": "<anystring>", "lastname": "<anystring>", "birthdate": "<anydate>", "maxWorkHours": 3, "username": "<anystring>", "permissions": "<anystring>", "lastUpdate": "<anydate>" });