Skip to content
Advertisement

Javascript cannot change the value of mydata

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?

Advertisement

Answer

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'
};
Advertisement