To keep track of an initializing/initialized object I want to create a discriminated union with a boolean. And so I wrote the following code:
interface InitializingThing extends BaseThing {
initialized: false;
value: undefined;
}
interface InitializedThing extends BaseThing {
initialized: true;
value: number;
}
type Thing = InitializingThing | InitializedThing;
const thing: Thing = { initialized: false, value: undefined };
console.log(thing);
getThing().then((value: number) => {
thing.value = value;
thing.initialized = true;
}).then(() => {
if (!thing.initialized) {
return;
}
console.log(15 + thing.value);
});
(see on the Typescript playground )
However this gives the errors
Type 'number' is not assignable to type 'undefined'.(2322)
Type 'true' is not assignable to type 'false'.(2322)
I can see from hovering over the console.log(thing) that the type is InitializingThing instead of Thing! Which seems to be the root of the problem, but I'm not sure why the TS compiler would do this.