Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to access nested interface types

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

like image 701
Sarah Avatar asked Jun 27 '26 14:06

Sarah


1 Answers

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;
}
like image 84
Dethariel Avatar answered Jul 01 '26 01:07

Dethariel



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!