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

178
Vistas
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 Respuestas
Responde la pregunta

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 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