I have an interface that has a second interface as a value as below. But when I try to access the nested values, I get an error. What is the correct way to access nested interface values?
interface Results {
pass: number;
fail: number;
}
interface Build {
name: string;
results: Results;
}
var obj: Build = {
name: "test",
results: {
pass: 3,
fail: 2
}
}
Currently, I'm trying to access it like so with no luck:
obj.results.pass
Error I'm getting: ERROR TypeError: Cannot set property 'pass' of undefined
The error you have is a runtime error (JavaScript execution engine), not a compilation one (TypeScript compiler).
This occurs because you have obj.results equal to undefined:
const test: Build = {};
test.results.pass; // ERROR TypeError: Cannot set property 'pass' of undefined
I would recommend that you check results property value before accessing its child property:
if (test.results) {
test.results.pass;
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With