When I have a type that can be something or undefined, I can easily use an if statement to check it contains something:
type MaybeString = string | undefined;
function useMaybeString(arg: MaybeString) {
if (arg !== undefined) {
printString(arg);
}
}
function printString(arg: string) {
console.log(arg)
}
But this example where my type can be one of two posibilities doesn't work:
type Foo = {foo: string};
type Bar = {bar: string};
type FooOrBar = Foo | Bar;
function useFooOrBar(arg: FooOrBar) {
if (arg.foo !== undefined) {
console.log(arg.foo);
} else {
console.log(arg.bar);
}
}
What is the solution? And why does TypeScript complain?