Search code examples
typescriptvariablesinitializationundefinedlet

TypeScript - No "Variable is used before being assigned" inside a function


I would like to understand the following TypeScript behavior:

The following code

let a: number
if (a === undefined) {
    console.log("how?")
}

throws an error: "Variable 'a' is used before being assigned.".

But the following code

let a: number
const f = (): void => {
    if (a === undefined) {
        console.log("how?")
    }
}
f()

works just fine and logs "how?".

Why is that? And also, how come a === undefined if its type is number?


Solution

  • There's an open issue about this in the Typescript GitHub project. It's a limitation of typescript's technical design.

    From Ryan Cavanaugh, it's

    because we don't inline the flow-control effects of functions