【问题标题】:ts-check error: property does not exist on typets-check 错误:类型上不存在属性
【发布时间】:2018-09-15 05:22:05
【问题描述】:

我有一个节点代码库,我想将它迁移到 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 会给出以下错误:

“请求”类型上不存在属性“clientIP”。

我应该怎么做才能让这个错误消失? 谢谢

【问题讨论】:

    标签: node.js typescript express


    【解决方案1】:

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

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

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2018-11-30
      • 2021-01-11
      • 2021-01-10
      • 1970-01-01
      • 2022-11-30
      • 1970-01-01
      • 2023-01-10
      • 1970-01-01
      相关资源
      最近更新 更多