I have an object in TypeScript with a boolean property. When I set the object's value to false, TypeScript assumes it will stay false (at least until the end of the scope), even though it's able to be changed:
const object = { property: true }; // Type is { property: boolean }
object.property = false; // Type is now { property: false }
function setObjectPropertyTrue(object: { property: boolean }) {
object.property = true;
}
setObjectPropertyTrue(object);
if (object.property == true) { // ← tsc: "This condition will always return false"
console.log("Object property is true!");
}
Here, the TypeScript compiler thinks the if statement will never succeed because as soon as I set the object's property to false, it assumes the property's type becomes false.
Of course I can cast object.property back to boolean in the if statement to fix the error, but this seems like a bad way of doing it? Ideally TypeScript wouldn't assume an object's property couldn't change after where it sees it is set.