Reputation: 675
I have a node code base and I want to migrate it to typescript. So the first thing I did was to add //@ts-check and fix the issues that typescript had. I could solve all the issues except for this one.
I need the client's ip address for the purpose of blacklisting clients that send too many redundant requests. So I use the middleware below to add the client's ip address to the request object.
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()
})
But when I want to access the clientIP property elsewhere, typescript gives the error below:
Property 'clientIP' does not exist on type 'Request'.
What should I do to make this error go away? Thanks
Upvotes: 1
Views: 764
Reputation: 30879
You'll need to augment the Request
interface in the express-serve-static-core
module with the new property. (According to the typings, the express
module has a Request
interface that extends the one in express-serve-static-core
, but augmenting this one will not cover all uses.) Put the following in a .d.ts
file in your project:
declare module "dummy" {
module "express-serve-static-core" {
interface Request {
clientIP: string;
}
}
}
The outer module declaration is needed to make the inner module declaration an "augmentation" instead of shadowing the original module, as mentioned in this thread. That trick is unfortunately not properly documented AFAIK.
Upvotes: 1