[Fixed] TypeScript Cannot read property of undefined – Angular 7

Issue

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: '' })
}

Solution

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;

Leave a Reply

(*) Required, Your email will not be published