When utilizing code similar to the one below, one would assume that TypeScript could infer that badObj
is a valid argument for fn
, as it should have the type Bad
.
Interestingly, within the body of fn
there seems to be no issue. However, when calling fn(badObj)
, an error occurs at the bottom. The same happens with fn(goodObj)
.
Is there a way to modify this code to achieve the expected behavior?
interface Ok {
ok: true;
date: undefined;
}
interface Bad {
ok: false;
date: Date;
}
const badObj = { ok: false, date: new Date()};
const goodObj = { ok: true, date: undefined}
const fn = (obj: Ok | Bad) => {
console.log(obj.ok);
if (!obj.ok) {
const minutes = obj.date.getMinutes();
}
};
fn(badObj)
fn(goodObj)
/*
The following error is thrown on the invocation of `fn(badObj)` and `fn(goodObj)`
Argument of type '{ ok: boolean; date: Date; }' is not assignable to parameter of type 'Ok | Bad'.
Type '{ ok: boolean; date: Date; }' is not assignable to type 'Bad'.
Types of property 'ok' are incompatible.
Type 'boolean' is not assignable to type 'false'.(2345)
*/
*/