Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

237
Vistas
Typescript does not detect condition in callback - Vue

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?

about 4 years ago · Juan Pablo Isaza
1 Respuestas
Responde la pregunta

0

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

about 4 years ago · Juan Pablo Isaza Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda