gpt4 book ai didi

typescript - 在 TypeScript 中增加默认导出?

转载 作者:行者123 更新时间:2023-12-05 05:29:49 25 4
gpt4 key购买 nike

有些包只导出一个对象。如果我要覆盖/扩展该对象:我会怎么做?

在搜索了很多答案之后,这就是我所在的地方:

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();

这个问题不是这里覆盖axios是否实用

最佳答案

TypeScript 具有声明合并功能,不幸的是,在您的情况下,您将无法利用它,因为它的 limitations :

Disallowed MergesNot 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.

如文档所述,另一方面,您可以利用 mixins创建您自己的扩展 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

关于typescript - 在 TypeScript 中增加默认导出?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/74843916/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com