typeScript расширение типов
пытаюсь написать рекурсивную API столкнулся с проблемой определения типов
const createInstanceHere = function (url: string): AxiosInstance {
const axiosInstance: AxiosInstance = axios.create({ baseURL: url, headers: {} });
axiosInstance.interceptors.response.use(
response => {
if (response.data?.error !== undefined) {
const textError: string = response.data.error;
notification.error(`При запросе произошла ошибка:${textError}`);
}
return response;
},
error => {
notification.error(error.toString());
}
);
return axiosInstance;
};
const api: AxiosInstanceRecursive = {
createChildInstance: function (nameSpace: string) {
let baseUrl: string;
if (this.defaults === undefined) {
baseUrl = 'url/';
} else {
baseUrl = this.defaults.baseURL === undefined ? 'uel/' : this.defaults.baseURL;
}
const newInstanceBaseUrl = nameSpace === '/' ? baseUrl : `${baseUrl}${nameSpace}`;
const newCurrentInstance = createInstanceHere(newInstanceBaseUrl);
return { ...newCurrentInstance, createChildInstance: this.createChildInstance, parent: this };
}
};
сам тип
export interface AxiosInstanceRecursive extends AxiosInstance {
(key?: keyof AxiosInstance): AxiosInstance;
parent?: AxiosInstanceRecursive;
createChildInstance: (param: string) => AxiosInstanceRecursive;
}
соотвественно получаю ошибку
вопрос как правильно это сделать или что я делаю не так?
Ответы (1 шт):
Автор решения: Roman
→ Ссылка
Решилось следующщим образов : завел 2 разных типа
/** @format */
import { AxiosInstance } from 'axios';
export interface AxiosInstanceRecursive extends AxiosInstance {
(key?: keyof AxiosInstance): AxiosInstance[keyof AxiosInstance];
parent: AxiosInstanceRecursive & AxiosInstance;
createChildInstance: (param: string) => AxiosInstanceRecursive & AxiosInstance;
}
export interface AxiosObject {
defaults?: any;
createChildInstance: (param: string) => AxiosInstanceRecursive & AxiosInstance;
}
в коде
const api: AxiosObject = {
createChildInstance: function (nameSpace: string): AxiosInstanceRecursive {
let baseUrl: string;
if (this.defaults === undefined) {
baseUrl = '/';
} else {
baseUrl = this.defaults.baseURL === undefined ? '/' : this.defaults.baseURL;
}
const newInstanceBaseUrl = nameSpace === '/' ? baseUrl : `${baseUrl}${nameSpace}`;
const newCurrentInstance = createInstanceHere(newInstanceBaseUrl);
return <AxiosInstanceRecursive>{ ...newCurrentInstance, createChildInstance: this.createChildInstance, parent: this };
}
};
