My angular component relies on the API Response for its functionality. I receive these responses from an external API.
When there are no errors
Data : { Status: string; Data: number; }
When an error occurs, this is what I get.
Data : { Status: string; Error: string; Message: string; }
Since 'Status' is a common property, I have attempted to unify the response structures using interfaces.
interface ApiModel {
Status: string;
}
interface DataModel extends ApiModel {
Data: number;
}
interface ErrorModel extends ApiModel {
ErrorCode: string;
Message: string;
}
I am utilizing TypeScript to define my variable with multiple possible types and pass that type in the response.
I prefer not to use optional types to avoid potential issues.
What I aim for is,
if (typeof Response === DataModel){
Response: DataModel;
// Other code
}
else {
Response: ErrorModel;
// Other code
}
Here is how the API call is structured:
getReminder(reminderId: number) {
const API_URL = `${this.BASE_URL}users/${this.userId}/reminders/${reminderId}`;
return this.httpClient.get<ErrorModel | DataModel>(API_URL, this.options).pipe(
map((data: ErrorModel | DataModel) => {
return data;
})
);
}