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

183
Visualizações
Typescript Error: Variable 'resWithStatus' is used before being assigned. ts(2454)
for (const item of filesForUpload) {
  let resWithStatus: IResponseType;
  try {
    const res = await uploadFile(item);
    resWithStatus = {
      id: res?.id,
      name: res?.name,
      link: res?.link,
      ext: res?.ext,
      status: "SUCCESS",
    };
  } catch (err) {
    resWithStatus = {
      id: uuidv4(),
      name: item.name,
      link: URL.createObjectURL(item),
      status: "FAILED",
    };
    console.log(err);
  } finally {
    const indexInUploadedImageState = newFileArray.findIndex((imageItem) => {
      if (
        resWithStatus.status === "FAILED" &&
        imageItem.name === resWithStatus.name
      )
        return true;
      if (
        resWithStatus.status === "SUCCESS" &&
        getFileNameWithoutExt(imageItem.name) === resWithStatus.name &&
        getFileExt(imageItem.name) === resWithStatus.ext
      )
        return true;
      return false;
    });

    console.log(resWithStatus); // Error occurs here
  }
  console.log(resWithStatus);
}

So I have this piece of code written in TS, I have declared a variable with let keyword with type inside the loop body, but I'm still getting the Error: Variable is used before it is assigned. As far as I know shouldn't this variable resWithStatus be available in all blocks of try, catch and finally as it's declared outside of them and used inside them. I'm fairly new to TS but get that it's not able to reference the outer resWithStatus variable which I don't get why.

about 4 years ago · Juan Pablo Isaza
1 Respostas
Responde à pergunta

0

You are right about the try, catch, and finally having access to the resWithStatus variable. But the error is saying resWithStatus is used before it is assigned. And I think in this case, since resWithStatus is not initialized(let resWithStatus: IResponseType;), TS can't guarantee that it has a value when it is being read from in your finally block. I think something like

let resWithStatus: IResponseType = {/*initialize resWithStatus*/};

should fix it.

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