Используйте дженерик параметры
export type ApiResponse<T> =
| { errors: Array<{ [key: string]: string }> }
| { data: Array<T> }
| { text: string };
abstract class Api<T> {
protected readonly baseUrl: string;
protected readonly endPoint: string;
protected get url(): string {
return new URL(this.endPoint, this.baseUrl).toString();
}
protected constructor(baseUrl = '/', endPoint: string) {
this.baseUrl = baseUrl;
this.endPoint = endPoint;
}
protected async http({
url = '',
method = 'GET',
data = undefined,
}: RequestData): Promise<ApiResponse<T>> {
try {
const response: Response = await fetch(
(new URL(url, this.url).toString()),
{ method, body: data }
);
return await response.json();
} catch (e) {
console.error(e.message);
return { text: e.message };
} finally {
// finnally
}
}
}
class ApiPost extends Api<Post> {
constructor(baseUrl: string, endPoint: string) {
super(baseUrl, endPoint);
}
async list(count?: number): Promise<false | Array<Post>> {
const response: ApiResponse = await this.http({
url: `${count ? `?_limit=${count}` : ''}`,
});
if (Array.isArray(response))
return response;
return false;
}
}