While people have asked similar questions, none of those answers are solving my problem. I'm in TypeScript 2.9.2 and I'm trying to add a context object to the Express Request object. I want to do it in a .d.ts
file.
What I currently have is this:
express.d.ts
declare namespace Express {
interface Request {
context: any;
}
}
However, it won't compile because `Property 'context' does not exist on type 'Request'.
In my other files, Webstorm claims the Request type is getting imported from the proper file.
I was under the impression that I could take advantage of declaration merging and not have to import or export a type definition.
Is this incorrect?
The "Property does not exist on type Request" error occurs when we access a property that does not exist in the Request interface. To solve the error, extend the Request interface in a . d. ts file adding the property you intend to access on the request object.
The res. locals is an object that contains the local variables for the response which are scoped to the request only and therefore just available for the views rendered during that request or response cycle.
Express body-parser is an npm module used to process data sent in an HTTP request body. It provides four express middleware for parsing JSON, Text, URL-encoded, and raw data sets over an HTTP request body. Before the target controller receives an incoming request, these middleware routines handle it.
Express. js Request and Response objects are the parameters of the callback function which is used in Express applications. The express. js request object represents the HTTP request and has properties for the request query string, parameters, body, HTTP headers, and so on.
Just a small modification for this to work:
declare namespace Express {
export interface Request {
context: any;
}
}
When we define an interface (or, in fact, anything from constants to classes) inside namespace, it's visible by default only for the members of the same namespace, as stated in the handbook. By adding export
we let TypeScript know that this interface must be used by the outside code, and it will be correctly merged into the existing declaration.
This is not a true export, as it would be from the module (on the top level), since the namespace itself is declare
d, not export
ed. So you just import it from module as usual:
import * as express from 'express';
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With