Reputation: 645
I have an API that returns this type of result:
{ "success": true, "result": {} } // on success
{ "success": false, "message": "Nope!" } // on failure
I tried to create an alternate type like so:
interface ResultSuccess<T> {
success: true;
result: T;
}
interface ErrorMessage {
success: false;
message: string;
}
type Maybe<T> = ResultSuccess<T> | ErrorMessage;
function HandleAPICall(response: Maybe<APIResult>) {
if (response.success) {
DoSomething(response.result);
} else {
console.log(response.message);
}
}
However on the console.log
statement i get an error like this:
Error TS2339 (TS) Property 'message' does not exist on type 'Maybe<APIResult>'.
Property 'message' does not exist on type 'ResultSuccess<number>'.
\maybe.ts 15 Active
How do I get the ErrorMessage from the Maybe?
Upvotes: 1
Views: 42