【问题标题】:How do I extend the default type of NPM packages?如何扩展 NPM 包的默认类型?
【发布时间】:2020-10-16 00:09:45
【问题描述】:

我们可以使用“声明模块”来扩展模块的类型。

例如:

// typings/node-fetch.d.ts
import 'node-fetch';
declare module 'node-fetch' {
    function kk(): void;
}

// src/index.ts
import fetch, { kk } from 'node-fetch';
kk(); // ok

但这是功能的扩展。

现在我想扩展 fetch 本身。

我想要这个效果:

// src/index.ts
import fetch from 'node-fetch';
fetch.foo();

node-fetch 本身的声明文件如下所示:

// node_modules/@types/node-fetch/index.d.ts
declare function fetch(
    url: RequestInfo,
    init?: RequestInit
): Promise<Response>;

declare namespace fetch {
    function isRedirect(code: number): boolean;
}

export default fetch;

如何扩展 fetch 的类型?

我试过了。它不起作用:

// typings/node-fetch.d.ts
import fetch from 'node-fetch';

declare module 'node-fetch' {
    namespace fetch {
        function foo(): void;
    }
    export default fetch; // Error, Exports and export assignments are not permitted in module augmentations
}

请问你想怎么解决。

谢谢!

【问题讨论】:

    标签: typescript typescript-typings typescript2.0 typescript-generics typescript1.8


    【解决方案1】:

    我相信您需要做的是使用如下所示的 interface 关键字:https://stackoverflow.com/a/56861261/106625

    【讨论】:

    • 谢谢!但它不能解决它。我想使用'fetch.kk',你得到的这种方式将是一个接口。请问还有什么吗?
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-28
    • 2013-01-24
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-05-03
    • 1970-01-01
    相关资源
    最近更新 更多