Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to extend @types/express request interface?

Tags:

typescript

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?

like image 733
dkimot Avatar asked Jun 28 '18 15:06

dkimot


People also ask

Does not exist on type request?

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.

What is RES locals?

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.

What is request Body express?

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.

What are request and response objects in express?

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.


1 Answers

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 declared, not exported. So you just import it from module as usual:

import * as express from 'express';
like image 175
Cerberus Avatar answered Oct 23 '22 21:10

Cerberus