Home > Mobile >  Typescript does not detect condition in callback - Vue
Typescript does not detect condition in callback - Vue

Time:01-05

In my Vuex store's state, I have a foo object that can possibly be null. So, before accessing one of its property (id for example), I have to check that this.$store.state.foo is not null.

It works well all the time, but it seems that TypeScript does not detect the condition in an axios callback:

private join(): void {
    if (this.$store.state.foo) { // <- condition to check that `this.$store.state.foo` is not null
      this.axios.post(`/foo/${this.$tstore.state.foo.id}/join`) // <- No error here
        .then((response) => {
          // ... some code
          this.$router.push({
            name: 'bar',
            params: { id: this.$tstore.state.foo.id } // <- TS error here, foo is potentially null
          });
        })
        .catch((error: AxiosError) => {
          // ... some code
        });
    }
  }

I can obviously check again if this.$store.state.foo is not null in the callback, but it there a way to tell TypeScript to detect the upper scope condition?

CodePudding user response:

You need to capture your variable - TS assumes that the value of foo might have become undefined by the time the callback runs.

Check a simpler example:

class X {
  foo: string | undefined;

  print = (x: string) => console.log(x);

  private join(): void {
    if (this.foo) { 
      setTimeout(() => {
        this.print(this.foo);   // ERROR
      }, 1000);
    }
  }

  private joinWithCapture(): void {
    const fooCapture = this.foo;
    if (fooCapture) { 
      setTimeout(() => {
        this.print(fooCapture); // OK
      }, 1000);
    }
  }
}

Playground

  •  Tags:  
  • Related