Is there a way to create an instance of the Customer class from a Json object without facing type safety issues?
I attempted to use the plainToInstance function from class-transformer but encountered difficulties obtaining the correct class instance in Typescript.
What am I doing wrong?
Import
import { plainToInstance } from 'class-transformer';
Customer JSON
const json = `{
"id": "1",
"name": "Jogn",
"surname": "Doe",
"email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="80eaaee4efe5aef4e5f3f4c0e7ede1e9ecaee3efed">[email protected]</a>",
"phone": "123456789"
}
}
`;
Customer class definition
import { Field, ObjectType, Directive, ID } from '@nestjs/graphql';
import { Address } from './address';
@ObjectType()
@Directive('@key(fields: "id")')
export class Customer {
@Field(() => ID)
id: string;
@Field()
name: String;
@Field({nullable: true})
surname?: String;
@Field()
email: String;
@Field({nullable: true})
phone?: String;
@Field()
customerType: String;
@Field()
customerStatus: String;
@Field(() => [Address], { nullable: true })
addresses?: [Address]
}
Transformation from Json to Customer instance
let customer : Customer = plainToInstance(Customer, json) as Customer;
console.log('customer.email);
Console result
Customer email: undefined
Unfortunately, I couldn't retrieve the email of the customer using this method
This is what happens when I log the entire customer variable
console.log(customer);
{
"id": "1",
"name": "Jogn",
"surname": "Doe",
"email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="d0bafeb4bfb5fea4b5a3a490b7bdb1b9bcfeb3bfbd">[email protected]</a>",
"phone": "123456789"
}
Test with creating the Customer instance inline
var x = new Customer();
x.id = "123";
console.log(x)
After trying this approach, the object looks proper in the console
Customer { id: '123' }