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.
CodePudding user response:
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.