The following interface is used to define a JSON API response.
The status field tells whether the request was successful or not.
The data filed is used to set data(only if available) returned by the server upon successful requests.
Similarly the message field is used to set error messages upon failed requests.
export interface IResponse<T> {
status: 'success' | 'fail';
data?: T;
message?: string;
}
Suppose I have the following function that fetches some company data from the server.
The response contains either data or string.
search(keyword: string): Observable<IResponse<ICompany[]|string>> {
return this.searchCompany(keyword);
}
When I try to call this function as follows, I get a compile error as data could either be ICompany[] or string.
this.dataImportService.search('')
.subscribe(
data => {
data.data[0].company_name // compile error
}, err => {
});
What should I do to get rid of this compile error?
data.data[0].company_name?