I am currently trying to convert my received JSON Object into a TypeScript class with the same attributes and I cannot get it to work. What am I doing wrong?
i like to use a littly tiny library called class-transformer.
it can handle nested-objects, map strings to date-objects and handle different json-property-names a lot more.
Maybe worth a look.
import { Type, plainToClass, Expose } from "class-transformer";
import 'reflect-metadata';
export class Employee{
@Expose({ name: "uid" })
id: number;
firstname: string;
lastname: string;
birthdate: Date;
maxWorkHours: number;
department: string;
@Type(() => Permission)
permissions: Permission[] = [];
typeOfEmployee: string;
note: string;
@Type(() => Date)
lastUpdate: Date;
}
export class Permission {
type : string;
}
let json:string = {
"uid": 123,
"department": "",
"typeOfEmployee": "",
"firstname": "",
"lastname": "",
"birthdate": "",
"maxWorkHours": 1,
"username": "",
"permissions": [
{'type' : 'read'},
{'type' : 'write'}
],
"lastUpdate": "2020-05-08"
}
console.log(plainToClass(Employee, json));
```