Consider this scenario:
type GeneralAPIError = {
status: "error";
message: string;
};
type Foo = {
status: string;
whatever: string;
}
function wat(): Foo | GeneralAPIError {
return Math.random() > .5 ? {
status: "error",
message: "noooo"
} : {
status: "success",
whatever: "yayyy"
};
}
const eh = wat();
// This doesn't work
console.log(eh.whatever || eh);
// Neither does this
if(eh.hasOwnProperty("whatever")) {
console.log(eh.whatever)
} else {
console.log(eh);
}
// This does, but the "as" is pretty ugly
if(eh.hasOwnProperty("whatever")) {
console.log((eh as Foo).whatever);
} else {
console.log(eh);
}
What is the optimal way to define the return type of wat()
?
In reality, it makes an API request that might result in error JSON (type GeneralAPIError
) or success JSON (type Foo
). The same error type is used for many similar functions.
The code towards the end that checks for a specific key within an object works correctly, but TypeScript raises some errors:
Property 'whatever' does not exist on type 'GeneralAPIError | Foo'. Property 'whatever' does not exist on type 'GeneralAPIError'.
In the first two examples. It seems like there should be a way to type the function return so that eh.whatever || eh
functions properly. What am I overlooking?