我有以下功能,应该列出AWS S3 bucket中的所有顶级文件夹。它使用了 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'类型,因为它没有类型注解,并且在它自己的初始化器中被直接或间接引用。
我不明白,因为应该很容易推断出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版本,我已经启用了所有严格的类型检查选项。
Typescript在循环和其他控制结构中进行类型推理。同时,在 ListObjectsV2Command
的输入和输出,以及以何种方式 s3Client.send
接受并返回。试着浏览这些类的类型定义,看看它是如何点击到位的。
我最好的猜测是,将未定义明确分配给 ContinuationToken
打破了类型推理,导致它解析为 any
当它接受一个可选的字符串时,就会出现这个错误。这与while循环和将推断的输出传递给同一个构造函数的输入一起导致了这个错误。
如果不把它分配给 undefined
(let ContinuationToken: string;
)应该可以使用,因为它的类型似乎将正确匹配为 string
在随后的运行中,在第一次运行中未定义。