In this scenario, I encountered a warning from TypeScript regarding an error in my toy example:
type obj = {
ok: "ok" | "error",
}
function main(a: obj){
a.ok = "ok";
reloadFromDatabase(a);
if (a.ok == "error"){ // TS error
console.log("Error");
}
}
// Any function that has side effects on object a.
// For example, typeorm's `a.reload()`
function reloadFromDatabase(a: obj){
a.ok = "error";
}
The specific error states:
This comparison seems accidental because the types '"ok"' and '"error"' have no overlap.(2367)
While it may seem logical to assume that mutating objects through side effects is not allowed, the type of a
is obj
, therefore both values (
"ok" | "error"
) should be permissible for obj.isOk
.
In this given code snippet where I can modify the function with side effects, everything works fine as I can simply return the mutated object:
function main(a: obj){
a.ok = "ok";
a = reloadFromDatabase(a);
if (a.ok == "error"){ // This time its fine
console.log("Error");
}
}
function reloadFromDatabase(a: obj){
a.ok = "error";
return a;
}
However, in my particular use case, I do not have access to the reloadFromDatabase
function and it does not return anything (it solely mutates the object).
Is there a TypeScript option to address this? Do you think this error is valid? Could there be potential situations where allowing mutation would compromise TypeScript's logic (leading to decreased or no type safety)?