NuvemDeLaranja
NuvemDeLaranja

Reputation: 23

TS ERROR: Cannot invoke an object which is possibly 'undefined' ts(2722)

I have the following problem:
Cannot invoke an object which is possibly 'undefined' ts(2722)

Example code:

class Foo {
    bar?: () => void
    configure(bar: () => void) {
        this.bar = bar
    }
    
    isConfigured(): boolean {
        return !!(this.bar)
    }
  
    foo() {
        if(!this.isConfigured()) throw new Error("...")
        this.bar()
    }

}

The error happens here:

this.bar()

Upvotes: 1

Views: 267

Answers (1)

Shalom Peles
Shalom Peles

Reputation: 2632

The simplest way is to use the Non-null assertion operator(!). This operator tells the compiler that you are sure that this property has a value even though it is declared nullable. It will look like this:

    foo() {
        if (!this.isConfigured()) throw new Error("...")
        this.bar!()
    }

Another way to do this is to define a user-defined type guard (See here to learn more about user-defined type guards):

class Foo {
    bar?: () => void
    configure(bar: () => void) {
        this.bar = bar
    }

    isConfigured(): this is { bar: () => void } {
                 // ^^^^^^^^^^^^^^^^^^^^^^^^^^^ This is type guard
        return !!(this.bar)
    }

    foo() {
        if (!this.isConfigured()) throw new Error("...")
        this.bar()
    }
}

Upvotes: 2

Related Questions