Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

236
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda