首页 > 解决方案 > 在这种情况下,为什么异步闭包会过度缩小变量类型?

问题描述

谁能解释为什么在 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 的分配也会产生错误,因为这也跨越了函数边界。我认为需要更多解释。

标签: typescript

解决方案


推荐阅读