Search code examples
angulartypescriptangular7

Create and assign a object property dynamically typescript


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


Solution

  • 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
    }