'TypeScript: Incorrect type inferring

The following code has the error "Variable 'b' is used before being assigned.(2454)":

let b: boolean
function f () {
    b = true
}
f()
console.log(b)

Similarly,

let b: boolean = false
function f () {
    b = true
}
f()
console.log(b === true ? "True" : "False")

gives the error: "This condition will always return 'false' since the types 'false' and 'true' have no overlap.(2367)".

Of course, this prints True.

Is this a bug or the result of a bad practice? What's the best alternative?

Edit: so far, the best workaround I've found for the second issue is to do let b = false as boolean so that the type of b is boolean. And use b! for the first issue.



Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source