3

Some packages export only a single object. If I were to overwrite/extend that object: How would I do that?

After searching a lot of answers this is where I am:

import axios from "axios";

declare module "axios" {
  const axios: {
    not: () => void;
  };

  export = axios; // <- Exports and export assignments are not permitted in module augmentations.
}

axios.not();

This question is not about whether it is practical to overwrite axios here

1 Answer 1

1

TypeScript has declaration merging abilities, unfortunately, in your case you won't be able to leverage it because of its limitations:

Disallowed Merges Not all merges are allowed in TypeScript. Currently, classes can not merge with other classes or with variables. For information on mimicking class merging, see the Mixins in TypeScript section.

As the documentation says, on the other hand you can leverage mixins to create your own class that extends Axios:

import { Axios } from "axios";

type AxiosConstructor = new (...args: any[]) => Axios;

function augmentAxios<T extends AxiosConstructor>(axios: T) {
    return class AugmentedAxios extends axios {
        newAbility() {}
    };
}

const AugmentedAxios = augmentAxios(Axios);

const augmentedAxios = new AugmentedAxios({});

augmentedAxios.post('http://test'); // Base ability
augmentedAxios.newAbility(); // New ability
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.