typescript - 为什么类构造函数的类型推断在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 版,并且我已经启用了所有严格的类型检查选项。
解决方案
Typescript 在循环和其他控制结构中进行类型推断。ListObjectsV2Command
输入和输出以及s3Client.send
接受和返回的内容也应该有一些类型匹配。尝试浏览这些类的类型定义,看看它是如何到位的。
我最好的猜测是明确分配 undefined 会ContinuationToken
破坏类型推断并导致它解析到它any
何时接受可选字符串。这与 while 循环一起并将推断的输出传递给同一构造函数的输入会导致此错误。
没有将它分配给undefined
( let ContinuationToken: string;
) 应该可以工作,因为似乎该类型将string
在后续运行中正确匹配并在第一遍传递 undefined 。
推荐阅读
- ajax - 简单的 wordpress ajax 查询不起作用
- c# - 不允许写入流 C#
- reactjs - 如何访问json数组中的嵌套对象属性反应
- c++ - 不应该保证复制省略适用吗?
- powerbi - 过滤到最新值的 DAX 查询
- android - 添加 Material Spinner 2.0.0 时出现 gradle 同步错误(未授权状态 401)
- android - 无法在 Titanium 中为 android 配置推送通知
- python - 使用自定义生成的字符串作为 django 中的模型字段值
- django - 如何有效地启动 python-Django 开发?
- angular - 是什么导致 Meteor Cordova 构建中出现白屏死机?