本文介绍了如何在项目范围内扩充模块?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用 fastify 和插件 fastify-static.我还在 typings/fastify-static/index.d.ts 中为这个插件提供了我自己的 TypeScript 类型声明:

I'm using fastify with plugin fastify-static. I also provide my own TypeScript types declaration for this plugin in typings/fastify-static/index.d.ts:

declare module "fastify-static" {
    import { Plugin } from "fastify";
    import { Server, IncomingMessage, ServerResponse } from "http";

    namespace fastifyStatic {
        const instance: Plugin<Server, IncomingMessage, ServerResponse, any>;
    }
    export = fastifyStatic.instance
}

另外,插件使用 sendFile 方法扩展了 fastify FastifyReply.

Additionally plugin extends fastify FastifyReply with method sendFile.

当我像这样在模块范围内增加 fastify 模块时,工作正常:

When I augment fastify module in module scope like this, works fine:

// server.js
import fastify from "fastify";
import fastifyStatic from "fastify-static";

declare module "fastify" {
    interface FastifyReply<HttpResponse> {
        sendFile: (file: string) => FastifyReply<HttpResponse>
    }
}

server.get("/file", async (request, reply) => {
    reply.sendFile('file')
});

不幸的是,它仅在此模块中有效.当我将声明移动到 typings/fastify-static/index.d.tstypings/fastify/index.d.ts 时,它会覆盖模块而不是增加.如何在项目范围内扩充 fastify 模块?

Unfortunately it works only in this module.When I move declaration to typings/fastify-static/index.d.ts or typings/fastify/index.d.ts it override module instead of augment.How can I augment fastify module in project scope?

推荐答案

Titian Cernicova-Dragomir 是对的.模块扩充在 typings/fastify-static/index.d.ts 中,但不是作为单独的模块声明.

Titian Cernicova-Dragomir was right. Module augmentation shout be in typings/fastify-static/index.d.ts, but not as separate module declaration.

// typings/fastify-static/index.d.ts

declare module "fastify-static" {
    import { Plugin } from "fastify";
    import { Server, IncomingMessage, ServerResponse } from "http";

    namespace fastifyStatic {
        const instance: Plugin<Server, IncomingMessage, ServerResponse, any>;
    }

    export = fastifyStatic.instance

    module "fastify" {
        interface FastifyReply<HttpResponse> {
            sendFile: (file: string) => FastifyReply<HttpResponse>
        }
    }
}

这篇关于如何在项目范围内扩充模块?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-07 20:53