node.js - ts 检查错误 : property does not exist on type

标签 node.js typescript express

我有一个 Node 代码库,我想将其迁移到 typescript 。所以我做的第一件事就是添加//@ts-check 并修复 typescript 存在的问题。除了这个问题之外,我可以解决所有问题。

我需要客户端的 IP 地址,以便将发送过多冗余请求的客户端列入黑名单。所以我使用下面的中间件将客户端的ip地址添加到请求对象中。

app.use((request, _, next) => {
    const ip = request.get('x-real-ip')
    if (ip) {
        Object.defineProperties(request, { clientIP: { value: ip, writable: false } })
    } else {
        Object.defineProperties(request, { clientIP: { value:request.socket.remoteAddress, writable: false } })
    }
    next()
})

但是当我想在其他地方访问 clientIP 属性时,typescript 会给出以下错误:

Property 'clientIP' does not exist on type 'Request'.

我应该怎样做才能消除这个错误? 谢谢

最佳答案

您需要使用新属性来扩充 express-serve-static-core 模块中的 Request 接口(interface)。 (根据类型,express 模块有一个 Request 接口(interface),该接口(interface)扩展了 express-serve-static-core 中的接口(interface),但扩展此接口(interface)并不能涵盖所有用途。)将以下内容放入项目中的 .d.ts 文件中:

declare module "dummy" {
    module "express-serve-static-core" {
        interface Request {
            clientIP: string;
        }
    }
}

需要外部模块声明来使内部模块声明成为“增强”,而不是隐藏原始模块,如 this thread 中所述。 。不幸的是,这个技巧没有被正确记录 AFAIK。

关于node.js - ts 检查错误 : property does not exist on type,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52312855/

相关文章:

javascript - 使用 NodeJs 将文本文件名保存到数据库

angular - 如何在 Angular 2 RC4 中获取查询参数

typescript 联合类型具有误导性

typescript - 我的 Angular 2 应用程序需要很长时间才能为初次使用的用户加载,我需要帮助来加快速度

api - 在 node.js 中管理基于命令的 TCP 套接字 API 上的连接

node.js - 如何在Three.js中从欧拉得到原始旋转四元数

node.js - 通过 mocha 将参数传递给程序

node.js - NodeJS 执行 then() 之后的下一个进程

node.js - 捕获 HTTP 响应事件

javascript - MERN 和 Redux : How do you pass Redux state data from Index to Show page?