首页 > 解决方案 > 为什么类构造函数的类型推断在while循环中不起作用

问题描述

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

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' 因为它没有类型注释并且在其自己的初始化程序中直接或间接引用。

我不明白,因为应该很容易推断出 command 是 type 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 版,并且我已经启用了所有严格的类型检查选项。

标签: typescriptaws-sdk-js

解决方案


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

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

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


推荐阅读