How to augment module in project scope?

一个人想着一个人 提交于 2019-12-11 16:48:02

问题


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
}

Additionally plugin extends fastify FastifyReply with method sendFile.

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')
});

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?


回答1:


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>
        }
    }
}


来源:https://stackoverflow.com/questions/52515196/how-to-augment-module-in-project-scope

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!