2

i have this email model:

export class Email{ to: Array< { email: string name: string } > from: { email: string name: string } cc: Array< { email: string name: string } > bcc: Array< { email: string name: string } > subject: string body: string type: string } 

Then I import the email model and declare it in the class like this:

import { Email } from '@/models/email'; export class BuilderJobComponent implements OnInit { emailJobData: Email 

Later on, inside a class method I try to set a value but I get undefined. What am I not understanding about this?

Cannot read property 'from' of undefined

this.emailJobData.from.email = email this.emailJobData.from.name = name // set the To address if( Recipient ){ this.emailJobData.to.push({ email: Recipient, name: '' }) } 

1 Answer 1

5

You declared variable emailJobData, but did not assign any value to it. Hence, it's value is undefined. And undefined doesn't have any properties.

The type after colon only defines the type that can be assigned to the variable, but does not assign any value.

In your code, replace

emailJobData: Email; 

with

emailJobData: Email = new Email(); 

And you should be good.

EDIT: To expand on fixing the issue, it's a good idea to have a constructor in your class that will initialize the values / objects in your class to the expected values. Of course, this depends on the business logic - sometimes you would expect undefined values instead of empty array / empty object, etc, so update accordingly - below is just an example.

export class AddressWithDisplayValue { email: string; name: string; } export class Email{ from: AddressWithDisplayValue; to: AddressWithDisplayValue[]; cc: AddressWithDisplayValue[]; bcc: AddressWithDisplayValue[]; subject: string; body: string; type: string; constructor() { this.from = new AddressWithDisplayValue(); this.to = []; this.cc = []; this.bcc = []; } } 

Then, after it was initialized with emailJobData = new Email() you will be able to set those properties, e.g.

this.emailJobData.from.email = email; 
Sign up to request clarification or add additional context in comments.

3 Comments

You are correct as that did fix the initial problem, but then I get, Cannot set 'email' of undefined, so from is now undefined. Is there any way around that, without explicitly setting from, like this: emailJobData.from = { name: '', email: '' } before i set the values?
I've edited the answer to cover that. You'll probably want to read up on how both JavaScript and TypeScript (which is compiled to JavaScript) work - there are some gotchas which might seem counter intuitive :)
Ahh, I see exactly what you mean now. I appreciate the answer :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.