Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to check if optional object property exists?

I’m having trouble getting TypeScript to recognise that an optional property of an object is defined.

type OuterKeys = 'a' | 'b';

type Inner = {
    value: '';
}

type Outer = Partial<Record<OuterKeys, Inner>>;

const thisGivesError = (key: OuterKeys, outer: Outer) => {
    if (outer[key]) {
        console.log(outer[key].value);
    }
}

Even though I explicitly check if outer[key] is defined, I’m getting error when trying to access outer[key].value: Object is possibly 'undefined'.

How can I work around it? The only way I found is assigning outer[key] to a variable and having another if, like below. Is this the only way to go?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

const thisWorks = (key: OuterKeys, outer: Outer) => {
    const o = outer[key];
    if (o) {
      console.log(o.value);
    }    
}

The playground with the code can be found here

Edit: I don’t want to use ! operator, as it feels like a workaround – why would I tell TypeScript that this value is set using non-null assertion, if I already checked for its existence with if? Same for .? – I already have the if, so this value for sure exists and is not optional.

>Solution :

That’s #10530, currently TS doesn’t narrow down on indexed access.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading