[Fixed] Javascript cannot change the value of mydata

Issue

I have this code:

mydata: null | { id: string } = null;

And after I try to add some values:

this.mydata.id = 'myidstring'; 

I keep getting:

ERROR TypeError: Cannot set property 'id' of null

How can I fix this?

Solution

You can’t set a property on null. You need to assign an object to your variable first:

let mydata: null | { id: string } = null;

mydata = {};
mydata.id = 'myidstring';

Or all in one go:

let mydata: null | { id: string } = null;

mydata = {
  id: 'myidstring'
};

Leave a Reply

(*) Required, Your email will not be published