0
votes

I have an interface declared like this,

export interface OurHistory {
  ourHistory?: object;
  step1?:object;
  step2?:object;
}

Inside the class, I have

export class HistoryComponent implements OnInit, OnDestroy {
  myHistory:OurHistory;

  let ourHistory = [];
  ourHistory = this.allHistory.fields['ourHistory'];
  this.myHistory.ourHistory = ourHistory[0];
}

I receive an error saying, Cannot set property 'ourHistory' of undefined

1
As myHistory variable is not initialized. By default it would be undefined. - flash
either instantiate the myHistory variable from a class that implements the interface i.e myHistory = new Hisory() or use something like myHistory: OurHistory = {}; - Madhav Sarpal

1 Answers

0
votes

This happens because on your second last line: this.myHistory is undefined. You are trying to access the property ourHistory of undefined, which the compiler does not like.

You need to instantiate the property, like mentioned in the comments to your question.

One way to do it, could do it like so:

export class HistoryComponent implements OnInit, OnDestroy {
  myHistory: OurHistory;

  let ourHistory = [];
  ourHistory = this.allHistory.fields['ourHistory'];
  this.myHistory = {ourHistory: ourHistory[0]};
}

This way, we instantiate the property myHistory with a new object:

{
   ourHistory: someValue
}