【问题标题】:How to augment module in project scope?如何在项目范围内扩充模块?
【发布时间】:2019-03-02 01:58:27
【问题描述】:

我正在使用 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
}

另外插件扩展了 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 模块?

【问题讨论】:

  • typings/fastify-static/index.d.ts 的定义是什么样的。您需要在此处添加增强
  • 它的覆盖模块而不是扩充它。我已经编辑了这个问题。感谢您的提示。

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


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 2014-05-24
    • 1970-01-01
    • 2018-11-25
    • 1970-01-01
    • 2022-08-14
    • 1970-01-01
    • 2020-02-25
    • 1970-01-01
    • 2022-12-10
    相关资源
    最近更新 更多