0

I have a class Article which has property of type Image and looks like this:

export class Article {
   public image:Image;
   public images: Image[]; 
}

If I comment this.article.image = new Image(); like this:

constructor()
{
    this.article = new Article();
    //this.article.image = new Image();
}

And If I try to use an this.image later in code, like:

 this.article.image.fileName = file.name;

I will get following error:

ERROR TypeError: Cannot set property '..' of undefined

But I realized in case when I try to add something to an array for example:

this.article.images.push(something);

I am not getting error! And I'm wondering why I don't get error when I use array (even if I did not said this.article.images = new Images[].. , and why I get error when I'm using simple object/not array..

2
  • What is image???can you show me the image class? Commented May 18, 2018 at 11:36
  • 1
    this.article.image is undefined, You havent assigned any value to it, You should create new Image object and assign it to this.article.image before setting file name like this -> this.article.image.fileName = file.name; Commented May 18, 2018 at 11:37

1 Answer 1

2

I guess the .. in your error code means fileName.

You actually explained the error yourself.

If I comment this.article.image = new Image();

You removed the creation of your image, thus, this.article.image is undefined.

So by using this.article.image.fileName, you are trying to access the property fileName of undefined.

However, for the property images, the method .push() already exists because it's a method defined by Array, which is known thanks to the declaration :

public images: Image[];
Sign up to request clarification or add additional context in comments.

2 Comments

To add to this, I think images works fine because of the declaration Image[]; .
I edited my answer to add the second part of the explanation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.