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

时间:2018-09-26 10:07:37

标签: node.js typescript typescript-typings strong-typing fastify

我正在将fastify与插件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
}

另外,插件使用方法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模块?

1 个答案:

答案 0 :(得分:0)

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