I have this code:
JavaScript
x
2
1
mydata: null | { id: string } = null;
2
And after I try to add some values:
JavaScript
1
2
1
this.mydata.id = 'myidstring';
2
I keep getting:
JavaScript
1
2
1
ERROR TypeError: Cannot set property 'id' of null
2
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:
JavaScript
1
5
1
let mydata: null | { id: string } = null;
2
3
mydata = {};
4
mydata.id = 'myidstring';
5
Or all in one go:
JavaScript
1
6
1
let mydata: null | { id: string } = null;
2
3
mydata = {
4
id: 'myidstring'
5
};
6