0

пытаюсь написать рекурсивную 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;
}

соотвественно получаю ошибку

введите сюда описание изображения

вопрос как правильно это сделать или что я делаю не так?

2
  • Если честно, то не очень понял что вы пытаетесь сделать. Поподробнее пожалуйста опишите что вы хотите сделать, чтобы пользователи не гадали 4 сен 2022 в 12:11
  • сори, сам разобрался, так что отпала необходимость
    – Roman
    4 сен 2022 в 12:21

1 ответ 1

0

Решилось следующщим образов : завел 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 };
  }
};

Ваш ответ

Нажимая на кнопку «Отправить ответ», вы соглашаетесь с нашими условиями использования и подтверждаете, что прочитали и поняли наши политику конфиденциальности и нормы поведения.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.