Reputation: 349
I have defined an object in TS like this:
reportObj : {
'report' : {
'pk' : '',
'uploaded' : '',
'sections' : {
'section1' : '',
'section2' : '',
'section3' : ''
}
}
};
I want to set the value of section1. How can I do this? I am trying:
this.reportObj.report.sections.section1 = data;
This fails and I get the error:
Uncaught (in promise): TypeError: Cannot read property 'report' of undefined
What am I doing wrong?
Upvotes: 0
Views: 7341
Reputation: 164139
The definition for the type should be:
reportObj: {
'report': {
'pk': string,
'uploaded': string,
'sections': {
'section1': string,
'section2': string,
'section3': string
}
}
};
Defining the variable/member type doesn't assign a value to it.
This:
let reportObj: {
report: {
pk: string,
uploaded: string,
sections: {
section1: string,
section2: string,
section3: string
}
}
};
console.log(reportObj.report);
Will fail at runtime because the variable reportObj
only has a type, but not a value.
To assign a value:
type Reporter = {
report: {
pk: string,
uploaded: string,
sections: {
section1: string,
section2: string,
section3: string
}
}
};
let reportObj = {} as Reporter;
console.log(reportObj.report); // undefined
But this will still throw a runtime error:
console.log(reportObj.report.pk);
This will assign the right value:
let reportObj = {
report: {
sections: {}
}
} as Reporter;
Upvotes: 1