I'm trying to fill class in typescript. But error 2779.
error TS2779: The left-hand side of an assignment expression may not be an optional property access.
Class
export class SendEmail {
sender?: ISender
}
interface ISender {
name: string
email: string
}
Declaration. Here I try fill my class.
let mail: SendEmail = new SendEmail();
mail.sender?.email = "[email protected]"; //<= error TS2779 here . If I try mail.sender!.email = "[email protected]", I have message Cannot set properties of undefined;
mail.sender?.name = "John Doe"
It's a simple example. I will have to fill in much larger class with subsub interface.
Thank you for help. I'm beginner in TS.
CodePudding user response:
The ?.
operator is not supported on the left hand side of an assignment (this is a JavaScript limitation)
You need to check for the sender before you assign it's fields:
if (mail.sender) {
mail.sender.email = "[email protected]";
mail.sender.name = "John Doe"
}
Although you might be better off actually assigning the sender and creating a new object:
mail.sender ={
email: "[email protected]",
name: "John Doe"
}