In the snippet below, an error is encountered:
example/not-following.ts:15:1 - error TS2722: Cannot invoke an object which is possibly 'undefined'.
15 run(true).maybe();
~~~~~~~~~~~~~~~
Snippet:
interface Example {
maybe?: () => void;
}
function execute(condition: boolean): Example {
const object: Example = {};
if (condition) {
object.maybe = (): void => {
console.log('maybe');
};
}
return object;
}
execute(true).maybe();
Despite being deterministic code, TypeScript fails to track its flow. Why does this happen?