Junior Dussouillez
Junior Dussouillez

Reputation: 2397

Non-null assertion operator required but value checked for non-null beforehand

I don't understand why the non-null assertion operator ! is required in my callback function because I check the value in the if before.

The compiler fails with error Object is possibly 'undefined'.

Of course using !.label works but I would like to understand why it doesn't in this case. Is that because of the "new scope" of my callback function ?

Live demo

interface Brand {
    label?: string;
}

class Component {

    public brand?: Brand;

    public readonly service = new Service();

    public process() {
        if (this.brand) {
            // this.brand.label = "ok"; // Works
            // this.service.process2(() => this.brand!.label = "ok"); // Works
            /*
            this.service.process2(() => {
                if (this.brand) {
                    this.brand.label = "ok";
                }
            });
            */ // Works
            this.service.process2(() => this.brand.label = "ok"); // Fails. Why ? Because of the new scope ?
        }
    }
}

class Service {

    public process2(callback: () => void) {
        callback();
    }
}

// Main
const comp = new Component();
comp.brand = {
    label: "foo"
};
comp.process();

It makes my ESLint analysis to fails because I enabled the rule no-non-null-assertion and I don't want to manually ignore these lines.

Upvotes: 0

Views: 536

Answers (1)

Egor Pashko
Egor Pashko

Reputation: 354

so, if (this.brand) just guarantees that this.service.process2 will be called.

But, your this.brand inside the callback which you pass inside this.service.process2 can be null or undefined when callback is called

Upvotes: 2

Related Questions