Как расширить модуль в рамках проекта? - PullRequest
0 голосов
/ 26 сентября 2018

Я использую fastify с плагином fastify-static .Я также предоставляю свое собственное объявление типов TypeScript для этого плагина в 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
}

Дополнительно плагин расширяет 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.ts или typings/fastify/index.d.ts, оно переопределяет модуль вместо дополнения. Как я могу дополнить модуль fastify в рамках проекта?

1 Ответ

0 голосов
/ 26 сентября 2018

Тициан Черникова-Драгомир был прав.Расширение модуля должно быть в 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>
        }
    }
}
...