Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

181
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!