【问题标题】:Why does type inference from class constructor not work inside while loops为什么类构造函数的类型推断在while循环中不起作用
【发布时间】:2020-10-03 20:19:30
【问题描述】:

我有以下函数应该列出 AWS S3 存储桶中的所有顶级文件夹。它使用 aws-sdk-js-v3,它本身是用 Typescript 编写的。

async function listTopLevelFolders() {
  let ContinuationToken: string | undefined = undefined
  do {
    // type inference does not work, command is of type any
    const command = new ListObjectsV2Command({       
      Bucket,
      ContinuationToken,
      Delimiter: '/',
    })
    const output = await s3Client.send(command)
    console.log(output.CommonPrefixes?.map((a) => a.Prefix))
    ContinuationToken = output.NextContinuationToken
  } while (ContinuationToken)
}

问题在于const command = new ListObjectsV2Command() 的行。我得到错误

'command' 隐式具有类型'any',因为它没有类型注释,并且在其自己的初始化程序中直接或间接引用。

我不明白,因为应该很容易推断该命令的类型为ListObjectsV2Command。令人惊讶的是,如果我注释掉 do {} while () 循环类型推断按预期工作并且代码编译没有错误

async function listTopLevelFolders() {
  let ContinuationToken: string | undefined = undefined
  // type inference works, command is of type ListObjectsV2Command
  const command = new ListObjectsV2Command({ 
    Bucket,
    ContinuationToken,
    Delimiter: '/',
  })
  const output = await s3Client.send(command)
  ContinuationToken = output.nextContinuationToken
}

我使用的是 Typescript 3.9.5 版,并且我已启用所有严格类型检查选项。

【问题讨论】:

  • 我找到了另一种编译方法:如果我没有在第一个示例中明确地将 undefined 分配给 ContinuationToken。似乎间接引用以某种方式来自 ContinuationToken(传递给命令)。

标签: typescript aws-sdk-js


【解决方案1】:

Typescript 在循环和其他控制结构中进行类型推断。此外,ListObjectsV2Command 中的输入和输出以及 s3Client.send 接受和返回的内容也应该有一些类型匹配。尝试浏览这些类的类型定义,看看它是如何到位的。

我最好的猜测是,将 undefined 显式分配给 ContinuationToken 会破坏类型推断,并导致它在接受可选字符串时解析为 any。这与 while 循环一起并将推断的输出传递给同一构造函数的输入会导致此错误。

如果没有将其分配给undefined (let ContinuationToken: string;),那么它应该可以工作,因为该类型似乎会在后续运行中正确匹配为string,并在第一次传递时传递 undefined。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2011-11-23
    • 2019-09-23
    • 2023-02-17
    • 1970-01-01
    • 1970-01-01
    • 2020-01-17
    相关资源
    最近更新 更多