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

Time:03-16

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.

CodePudding user response:

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

  • Related