Roman
Roman

Reputation: 35

How to make an interface for API response?

I have written API on PHP which have two different answers based on success status.

First response:

{
    "success": true,
    "data": {
         "prop1": "Great, it works!"
    }
}

Second response:

{
    "success": false,
    "data": {
         "prop2": "Something wrong!"
    }
}

How to write the interface correctly, so that after checking success, the editor understands what kind of answer is before him?

Upvotes: 1

Views: 3246

Answers (3)

JB Nizet
JB Nizet

Reputation: 691635

You can do it this way:

interface SuccessResponse {
  success: true;
  data: {
    prop1: string;
  };
}

interface ErrorResponse {
  success: false;
  data: {
    prop2: string;
  };
}

type Response = SuccessResponse | ErrorResponse;

This way, you can use

const r: Response = ...;
if (r.success) {
  console.log(r.data.prop1);
}

And the compiler won't let you use r.data.prop2.

For the other one, though, it seems you need an explicit comparison with false (probably not if you use strict null checks):

const r: Response = ...;
if (r.success === false) {
  console.log(r.data.prop2);
}

Upvotes: 2

Pranay Rana
Pranay Rana

Reputation: 176896

you can create interface like this

export interface  Response {
  success : bool;
  data : Data;
}
   export class Data {
      prop1?:string;
      prop2?: string;
      GetData() {
        return prop1 || prop2;
     }
   }

now based on success value you can check prop1 and pro2. you can do like this to make it working , as you dont want to choose property

const prodata = prop1 || prop2;

Upvotes: 0

nash11
nash11

Reputation: 8650

You can write it like this

interface MyResponse {
    success: boolean;
    data: MyResponseData;
}

interface MyResponseData {
    prop1?: string;
    prop2?: string;
}

Change the interface names to more meaningful ones as per your application. I have set prop1 and prop2 as optional (?) because your sample responses don't seem to have both as required.

Upvotes: 0

Related Questions