如何在项目范围内扩充模块?

How to augment module in project scope?

我正在使用 fastify with plugin fastify-static。我还在 typings/fastify-static/index.d.ts:

中为此插件提供了我自己的 TypeScript 类型声明
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
}

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

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

// 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 模块?

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

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