Michael Chen
Michael Chen

Reputation: 645

How do I type an alternate type with conditionally existent members?

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

Answers (1)

Oblosys
Oblosys

Reputation: 15106

You will need to enable strictNullChecks (docs) in your tsconfig.json for discriminated unions on boolean properties to work.

Upvotes: 1

Related Questions