1

Can anyone explain why in TypeScript the narrowing of a variable's type is undone within an async closure? Here is a minimal example of what I am talking about.

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

EDIT: the answer linked here does not seem to match what I am seeing with this example. If this was correct, then the assignment of str2 would also produce an error as this crosses function boundaries too. I think more explanation is required.

Chris_F
  • 4,991
  • 5
  • 33
  • 63

0 Answers0