我目前正在尝试将收到的 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);
链接到 Typescript Playground https://www.typescriptlang.org/play/#src=class%20Employee%7B%0A%20%20%20%20firstname%3A%20string%3B%0A%20%20%20%20lastname%3A%20string%3B%0A%20%20%20%20birthdate%3A%20Date%3B%0A%20%20%20%20maxWorkHours%3A%20number%3B%0A%20%20%20%20department%3A%20string%3B%0A%20%20%20%20permissions%3A%20string%3B%0A%20%20%20%20typeOfEmployee%3A%20string%3B%0A%20%20%20%20note%3A%20string%3B%0A%20%20%20%20lastUpdate%3A%20Date%3B%0A%7D%0A%0Avar%20e%3A%20Employee%20%3D%20new%20Employee()%3B%0AObject.assign(e%2C%20%7B%0A%20%20%20%20%22department%22%3A%20%22%3Canystring%3E%22%2C%0A%20%20%20%20%22typeOfEmployee%22%3A%20%22%3Canystring%3E%22%2C%0A%20%20%20%20%22firstname%22%3A%20%22%3Canystring%3E%22%2C%0A%20%20%20%20%22lastname%22%3A%20%22%3Canystring%3E%22%2C%0A%20%20%20%20%22birthdate%22%3A%20%22%3Canydate%3E%22%2C%0A%20%20%20%20%22maxWorkHours%22%3A%203%2C%0A%20%20%20%20%22username%22%3A%20%22%3Canystring%3E%22%2C%0A%20%20%20%20%22permissions%22%3A%20%22%3Canystring%3E%22%2C%0A%20%20%20%20%22lastUpdate%22%3A%20%22%3Canydate%3E%22%0A%7D)%3B%0Aconsole.log(e)%3B%0A