My TypeScript object has a boolean property that causes some confusion. When I update the object's value to false, TypeScript seems to believe it will remain false indefinitely (at least within the scope), even though it can be modified:
const obj = { prop: true }; // Type is { prop: boolean }
obj.prop = false; // Type now { prop: false }
function setPropToTrue(object: { prop: boolean }) {
object.prop = true;
}
setPropToTrue(obj);
if (obj.prop == true) { // ← tsc: "This condition will always return false"
console.log("Object property is true!");
}
The TypeScript compiler assumes that the if statement will never evaluate as true because when the object's property was set to false, it interprets the type of the property as false.
While it is possible to cast obj.prop back to a boolean in the if statement to resolve the issue, this approach may not be optimal. Ideally, TypeScript would not automatically assume that an object's property remains unchanged after the initial assignment.