Extend Express Request and Response : Typescript Declaration Merging

When we use  TypeScript to Build a Node API with Express, you might need to add some additional properties to the Express request and response object. To add extra properties to the request and response object you need to extend the response and request interface.

index.d.ts files are used to provide typescript type information about a module that’s written in JavaScript.For express, the index.d.ts is present inside the @types/express folder inside the node_modules folder.


As you can see in the index.d.ts file

The Request and Response extend core.Response and core.Request

Extending Request and Response Object with Declaration Merging

Declaration merging means that the compiler merges two separate declarations declared with the same name into a single definition.

See below example in which the interface declarations are merged in typescript

So boy Object can have all the properties of both the interfaces. If the declaration was not merged adding property mark to the Object could have caused “property does not exist” error

To achieve Declaration Merging with request and response interface follow these steps

1 Create a type.d.ts file in the root folder of the project and add the following code into it

2 Add the type.d.ts in the files of your tsconfig.json

Now let’s add a token property to the Request and Response in the following way

Without this extension, adding req.token and res.token will throw

Error:Property token does not exist in the type Response/Request


No Comments

Leave a Reply

Your email address will not be published. Required fields are marked *