0

I am running into an issue with a data Interface. My API returns me the data in a format which looks something like this

export interface IApiResponse {
    Success: boolean;
    Error: string;
    Message: string;
    RowCount: number;
    Data: [];
  }

this works fine as long as the Data is actually an array which is often the case. But when I get lets say the detail of a contact it is only a object in Data which is not an array. So my question is there a way to handle this or is the only way to create 2 interfaces where one is for a response where data is array the other when it is object.

1
  • You can specify two types like this: Data: Array | Object Commented Oct 19, 2020 at 19:18

1 Answer 1

1

You can pass a data type by defining the interface as follows:

export interface IApiResponse<T> {
  Success: boolean;
  Error: string;
  Message: string;
  RowCount: number;
  Data: T;
}

Then depending on your API endpoint, you can specify the type:

function someApiCall(): IApiResponse<MyDataType[]> {
  ...
}
Sign up to request clarification or add additional context in comments.

2 Comments

That works, i am wondering is there a way to use a default Datatype if T is not provided ? I am asking to see if there is a easy way to migrate which makes T optional and if T is not provided it would default to array.
@ConfusedCoder: You should be able to do something like interface IApiResponse<T = any[]> { ... }

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.