typescript - 在这种情况下,为什么异步闭包会过度缩小变量类型?
问题描述
谁能解释为什么在 TypeScript 中变量类型的缩小在异步闭包中被撤销?这是我正在谈论的一个最小示例。
import http from "http"
http.createServer(async (req) => {
// req.url is of type string|undefined
if (req.url === undefined) {
throw new Error()
}
// after checking for undefined req.url is now of type string
const str1: string = req.url // no error here
const str2: string = (() => { // no error here
return req.url
})()
const str3: string = await (async () => { // error
return req.url //here req.url is suddenly of type string|undefined again
})()
})
打字稿 2.8.1
编辑:此处链接的答案似乎与我在此示例中看到的不符。如果这是正确的,那么 str2 的分配也会产生错误,因为这也跨越了函数边界。我认为需要更多解释。
解决方案
推荐阅读
- r - 如何选择具有一定连续数的数据
- c# - 来自不同类的 Lambda 表达式中的多个 Where 子句
- python - 随机数,小数
- php - 我应该在 nginx.conf 或 Laravel config/cors.php 中添加我的 CORS 标头吗?
- svg - 对多维交叉滤波器求和以减少维数
- swift5 - 如何找到进度(Progress)对象的子级?
- amazon-web-services - 无法在 EC2 上创建 AudioDevices・Spring-Boot
- python - 交互失败 discord.py 按钮
- c# - 如何在变量字符串c#中插入双引号
- spring - 将 application.yml 文件(在我的应用程序中可用)读入 spring boot 中添加的依赖模块