Typescript Error: Variable 'resWithStatus' is used before being assigned. ts(2454)

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);
}

所以我用 TS 编写了这段代码,我在循环体内声明了一个带有 let 关键字和类型的变量,但我仍然得到 错误Variable is used before it is assigned。据我所知,这个变量 resWithStatus 不应该在所有 try、catch 和 finally 块中可用,因为它在它们外部声明并在它们内部使用。我是 TS 的新手,但知道它无法引用外部 resWithStatus 变量,我不明白为什么。

您关于 trycatchfinally 有权访问 resWithStatus 变量的说法是正确的。但是错误是说 resWithStatus 在分配之前被使用了。我认为在这种情况下,由于 resWithStatus 未初始化(let resWithStatus: IResponseType;),TS 不能保证它在您的 finally 块中读取时具有值。我觉得像

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

应该修复它。