有人可以解释为什么在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
})()
})
TypeScript 2.8.1
编辑:此处链接的答案似乎与我在此示例中看到的不一致。如果这是正确的,那么str2的赋值也会产生错误,因为它也会跨越函数边界。我认为需要更多解释。