Extend Express Request and Response : Typescript Declaration Merging
Typescript / February 12, 2019

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…

Share this page in social media platforms