Enhance the express Response type and then export my updated type as a distinct module

I am currently working on developing a new 'common' module for my team. One of the key features it should have is an extension of both the response and request objects in Express.

Our main goal is to achieve two things - first, extending the Request object to include a user property that will be initialized by a middleware responsible for authentication.

The second objective is to establish a consistent error handling convention. To achieve this, I plan to extend the response type of Express by adding a method called sendError. This method will take an exception or error message as input and generate the appropriate response. I want to go beyond simply extending an interface; I aim to provide implementation as well.

Thus far, I have created a new module where I added a file named types.d.ts and included it in my "types" section within the tsconfig.

import {User} from '../models/user.ts'
declare module 'express'{
    export interface Request {
        user: User;
    }
}

Within my module, I can successfully access the user property for requests, and everything functions smoothly. However, when another service installs this module via npm, it fails to recognize this property.

My second question pertains to achieving our secondary goal. This task involves more than just extending an interface; it resembles extending a class since I wish to provide implementation details.

One solution I considered is outlined below:

import {User} from '../models/user.ts'
declare module 'express'{
    export interface Response {
        sendError: (statusCode : number, error : Error ) => void;
    }
}

express.Response.sendError = //insert custom logic here 

Answer №1

Why not simply expand the namespace? This method has been effective for me:

I typically store a file at

<project-root>/types/express.d.ts
. In this scenario, the content would look like this:

import {User} from '../models/user.ts'
declare namespace Express{
  export interface Request {
    user: User
  }

  export interface Response {
    sendError: (statusCode : number, error :Error ) => void;
  }
}

Take a look at the Express DefinitelyTyped repository for more insights.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Issues with eventEmitter functionality in Angular 2

Everyone performed admirably following the manual, here is the code snippet for WebSocketBroadcaster: import {EventEmitter, Injectable} from "@angular/core"; @Injectable() export class WebSocketBroadcaster { ee: EventEmitter<any> = new EventEmi ...

"Comparing the use of single Angular libraries versus multiple libraries on npm

I am considering consolidating all my libraries (57 in total) into a single folder called @my-organisation/team. This is because each library has many dependencies on one another and managing versioning & dependencies separately would be difficult. After s ...

How to dynamically retrieve values from a const object literal using TypeScript

Currently, I am utilizing a TypeScript library known as ts-proto, which is responsible for generating TypeScript code. The resulting generated code resembles the following: //BasicMessage.ts export interface BasicMessage { id: Long; name: string; } ...

PlatypusTS: Embracing Inner Modules

Incorporating angular, I have the capability to fetch object instances or import modules using the $injector in this manner: export class BaseService { protected $http: angular.IHttpService; protected _injector: angular.auto.IInjec ...

Issues with the React router have been detected on a few specific pages of the live site

Check out my live website and view my code here When I execute npm start, all the links work perfectly fine. However, when I run npm run build, some of the page routes stop functioning properly. Specifically, the /about page doesn't load at all, and ...

Unable to continue due to being stuck in the "Starting packager" phase of React Native development

Whenever I attempt to start the React Native project (you can find it here), the npm start script gets stuck on Starting packager I have already checked these resources regarding the issue: react-community issue: 203 react-native-stuck-at-starting-packa ...

Union types discriminate cases within an array

Creating a union type from a string array: const categories = [ 'Category A', 'Category B' ] as const type myCategory = typeof categories[number] myCategory is now 'Category A' | 'Category B' Now, the goal is ...

Expanding the capabilities of i18next's translation function

I'm having trouble properly extending the function. I am stuck with the error Cannot redeclare block-scoped variable t. I am unsure if declaring a module is the correct approach (I am new to TypeScript). I have also tried creating a wrapper for the t ...

I am encountering difficulties with installing nodemon through the npm command

click here for the image Upon attempting to install the nodemon package through npm, I encountered errors as depicted in the linked image. Even after utilizing sudo, the issue persisted. ...

What is the best way to obtain a user's ID on the server side?

I'm currently working on a node.js application using express and I am in need of retrieving the user ID. I would like to have something similar to "req.userID" so that I can use it in the following way: var counter=0; var user = new Array(); router.g ...

Universal Angular along with Window's Innerwidth

Utilizing Window.Innerwidth in my Angular Project has been successful, however, I encountered an issue when attempting to implement it into Angular Universal. The content within window.innerwidth does not appear in the view source. Here is a snippet of my ...

Using Next.js and TypeScript to Send Props to Dynamically Typed Objects

I am in the process of developing an application using Next.js with TypeScript. I have encountered an error message stating Type 'VoidFunctionComponent<ShirtDetailProps>' is missing the following properties when passing props to a component ...

Is it advisable to incorporate await within Promise.all?

Currently, I am developing express middleware to conduct two asynchronous calls to the database in order to verify whether a username or email is already being used. The functions return promises without a catch block as I aim to keep the database logic se ...

Guide on Applying a Dynamic Color in VueJs 3 Composition API/Vuetify Using CSS

Currently, my project utilizes Vue 3 with the composition API and Vuetify for the UI. I am looking to utilize a color that is already defined in a Vuetify theme variable within my CSS, similar to how I have done it previously in JavaScript. Although I at ...

Passing variables through a promise chain and utilizing the finally method

My current endeavor involves constructing a log for an Express API, yet I am encountering difficulties in extracting the data for logging. I have successfully logged the initial req and res objects within the finally block, but I am uncertain about how to ...

Is it possible to use an Enum as a type in TypeScript?

Previously, I utilized an enum as a type because the code below is valid: enum Test { A, B, } let a: Test = Test.A However, when using it as the type for React state, my IDE displays an error: Type FetchState is not assignable to type SetStateActi ...

Refresh the settings and display the view

I have a dilemma where my view is only rendered after an axios request completes, but I actually need the view to load first. Then, once the request is complete, I can pass the parameter to the already loaded view. Currently: app.get('/', funct ...

Empty body Jade forms are returned to signify a Node.js POST request

Utilizing Jade alongside express and node.js, I am developing a frontend for a flight log database as part of my training. Despite ensuring that my inputs have names, setting my body parser to application/json, and placing my routes after middleware declar ...

What assistance is available for building a JavaScript package that integrates and utilizes all necessary dependencies?

I am looking for a solution to include a third-party library in a JavaScript file that will be downloaded to our project only when we visit a specific page. This library is installed with npm and I want it to be part of the js package without includi ...

Whenever I try to post a new order to my Firebase database, an error pops up saying "TypeError: Cannot read property 'numberOfSuits' of undefined."

When testing the code below on Postman, I encountered a typeerror (TypeError: Cannot read property 'numberOfSuits' of undefined). Additionally, when I removed the last three fields to only post the first two default fields, the data was successfu ...