【发布时间】: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