4

in following code with strictNullChecks turned on I'm getting an error

Object is possibly 'undefined'.

class Smth {
    private data: Array<{ value: number} | undefined> = [];

    public doSmth(i: number) { 
        const data = this.data;
        return data[i] && data[i].value === 0
        //                ^^^^^^^ Object is possibly 'undefined'.
    }
}

I can't understand how it can be undefined after a check.

5
  • 5
    Here's the related issue., TL;DR, typescript won't check this because of the compiler performance cost. In the meantime, you can use a non-null assertion: data[i]!.value === 0
    – CRice
    Commented May 7, 2018 at 22:49
  • I suggest not to use the same variable name on multiple locations of your code, although is possible to do it, it makes code confusing. You have a constant variable named "data" and also a private member of the class with the same name. Just ask yourself which one are you really using in your code? Commented May 7, 2018 at 22:53
  • @JonnathanQ, but they refer to the same object.
    – Qwertiy
    Commented May 7, 2018 at 23:02
  • @CRice, why not an answer?
    – Qwertiy
    Commented May 7, 2018 at 23:25
  • @Qwertiy, I thought there would have been a duplicate for sure and I was going to vote for that after commenting, but now I can't find one. I'll post it as an answer now.
    – CRice
    Commented May 7, 2018 at 23:29

1 Answer 1

1

This is a known issue in Typescript.

TL;DR of that issue, Typescript can make these checks but the devs have chosen not to due to a significant performance cost on the compiler.

The workaround is to use the non-null assertion operator (!) to tell the compiler that the value is not null or undefined. For this example:

return data[i] && data[i]!.value === 0
1
  • 2
    Another way (without using non-null assertion operator) is just to store an array item in its own variable: const item = this.data[i]; return item && item.value === 0;
    – Aleksey L.
    Commented May 8, 2018 at 5:03

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.