【问题标题】:Typescript Error: Variable 'resWithStatus' is used before being assigned. ts(2454)打字稿错误:在分配之前使用了变量“resWithStatus”。 ts(2454)
【发布时间】:2021-12-29 23:43:44
【问题描述】:
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 变量,我不明白为什么。

【问题讨论】:

  • 你能提供一个有这个错误的工作示例吗?也许在代码沙盒或类似的地方。
  • @MarcoNisi 我可以给你上下文。整个循环位于异步函数内部。我们使用 uploadFile 方法执行一些异步任务,在循环内部我已经声明了变量,我尝试将其设置为 trycatch 中的某个值,然后尝试在 finally 块内使用存储在该变量中的值因为变量本身是在 try、catch 和 finally 之外用 let 关键字声明的。但是当我尝试在 finally 块中访问该变量时,TS 会抛出错误 Variable is being used before it is assigned 但它会在任一块中分配一些东西。

标签: javascript typescript typescript-typings try-catch-finally


【解决方案1】:

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

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

应该修复它。

【讨论】:

  • 这解决了问题,但不会在 try 或 catch 块中将某些东西分配给变量吗?还有什么其他路径在到达 finally 块之前无法分配任何值?
  • 你知道,我知道,但是编译器不能确定。如果在 catch 块中为 resWithStatus 赋值之前有一些其他代码并且该代码引发了异常怎么办?这就是我可以解释的方式。相信对 TS 编译器有更多了解的人可以更准确的解释一下。
  • 即使在这种情况下,当URL.createObjectURL(item) 抛出异常时,当代码到达finally 块时resWithStatus 将是未定义的。
猜你喜欢
  • 2020-07-16
  • 2020-07-06
  • 2021-06-22
  • 2020-05-22
  • 2021-10-09
  • 1970-01-01
  • 1970-01-01
  • 2017-10-13
  • 2020-09-22
相关资源
最近更新 更多