Expanding current attributes within @types declarations

I want to enhance the Request object provided by express with additional data stored in the session. I attempted to create my own typings file (d.ts) and wrote this code snippet:

import * as express from 'express';

declare module 'express' {
    export interface Request {
        session: express.Request['session'] & {
            myOwnData: string;
        }
    }
}

However, I encountered the following error:

'session' is referenced directly or indirectly in its own type annotation.

Can someone advise on the correct approach to implement this functionality?

Answer №1

After examining the type declaration for express-session, it is clear that it defines a Session (and modifies the Request object) within the Express namespace. By utilizing this, we are able to create a custom type declaration (mySession.dt.s) to enhance the default properties without running into any issues with declaration merging:

import {Express} from 'express';
import 'express-session';

declare module 'express' {
    export interface Request {
        session: Express.Session & {
            myOwnData: string;
            myOwnData2: number;
            myOwnData3: boolean;
        };
    }
}

It is worth noting that the compiler appears to be somewhat flexible regarding imports in this file (such as not requiring explicit import of Express or

Request</code), but being specific will lead to more consistent results.</p>

<p>Subsequently, we can import this declaration into our server file:</p>

<pre><code>import express = require('express');
import {Express, Request, Response} from 'express';
import './mySession';
import * as session from 'express-session';

const app: Express = express();
const PORT = process.env.PORT || process.env.NODE_PORT || 3000;

app.use('/endpoint', (req: Request, res: Response) => {
   const a: number = req.session.myOwnData3 + 2; // triggers compilation error and flagged by text editors
   console.log(req.session.myOwnData); // compiles successfully and offers autocomplete in Webstorm
   // perform tasks
   return res.ok();
});

app.use(session(/** handle session operations **/));

log.info(`Starting Express Server on ${PORT}`);
app.listen(PORT);

As verified through testing, this setup ensures type safety for the added properties and facilitates intellisense/autocomplete in both VSCode and WebStorm for both the original express-session features and the additional properties.

Regrettably, as mentioned, these modifications do not have global application where type inference is utilized (only when explicitly importing Request). If complete control over the interface is desired, one option is to uninstall @types/express-session and manually adjust the d.ts file (and then import it). Alternatively, creating an entirely new property and implementation is possible, but considerably more labor-intensive.

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

Issue with Redis cache time-to-live not adhering to set expiration

I have encountered an issue while using IoRedis and DragonflyDB to implement rate limiting in my web application. Despite setting a TTL of 5 seconds for the keys in the Redis DB, sometimes they do not expire as expected. I am struggling to understand why t ...

Issue with Angular component inheritance where changes made in the base component are not being

click here to view the example on your browser base component import { Component, ChangeDetectorRef, OnInit, Input } from '@angular/core'; @Component({ selector: 'app-base-component', template: `<p> <b>base</b> ...

What is the best method for showing the name of the card?

I have developed a game using Angular that displays images of cards, but I am facing an issue in showing their names on the screen. At times, it displays the same name for all the cards or even incorrect names. In my TypeScript class 'Paquet', I ...

Conditionally show a button in an Angular application based on the truthiness of a boolean value

I'm currently developing a simple angular Single Page Application (SPA) for a Pizzeria. Within my application, I have an array that contains various types of Pizzas with string, number, and boolean data types. Using this array, I am dynamically gene ...

Issues with loading AddMarker on initial launch in Ionic 2

Can someone help me figure out what's causing the issue in my code? When I try to load a google map in my ionic 2 app, the marker doesn't show up the first time. It only appears when I reload the map for the second time or later. I also need ass ...

"I am looking for a way to incorporate animation into my Angular application when the data changes. Specifically, I am interested in adding animation effects to

Whenever I click on the left or right button, the data should come with animation. However, it did not work for me. I tried adding some void animation in Angular and placed a trigger on my HTML element. The animation worked when the page was refreshed, bu ...

Focusing in on a particular category of items based on a specific characteristic

I can't seem to understand why typescript has an issue with the code below. The errors from the compiler are detailed in the comments within the code. const FOO = Symbol(); function bar<T>(param: T) { if (param !== null && typeof para ...

having difficulty interpreting the information from angular's httpclient json request

After creating an Angular function in typescript to make an http request for JSON data and save it to an object, I noticed that the function requires two clicks of the associated button to work properly. Although the connection and data parsing are success ...

Leveraging import and export functionality in TypeScript while utilizing RequireJS as a dependency

I am in the process of transitioning a complex JavaScript application from Backbone/Marionette to TypeScript. While making this shift, I want to explore the benefits of exporting and importing classes using files as modules. Is it necessary to incorporat ...

Efficiently convert Map keys into a Set in Javascript without the need to copy and rebuild the set

Even though I am capable of const set = new Set(map.keys()) I don't want to have to rebuild the set. Additionally, I prefer not to create a duplicate set for the return value. The function responsible for returning this set should also have the abili ...

Guide on incorporating jQuery-extended bootstrap components in Angular

Currently, I am exploring the integration of the Bootstrap 3.3.7 popover component (since I cannot use the ng version) into a new Angular 4 application. To achieve this, I initially installed: npm install --save jquery @types/jquery bootstrap Following t ...

What is the best way to retrieve the data from a specific section when a checkbox is selected in Angular 2?

When I select a checkbox for any section and then click the submit button, I want to display the details of that section in the console. Can someone assist me with this? **Stackblitz link:** : https://stackblitz.com/edit/angular-q7y8k1?file=src%2Fapp%2Fa ...

What is a superior option to converting to a promise?

Imagine I am creating a function like the one below: async function foo(axe: Axe): Promise<Sword> { // ... } This function is designed to be utilized in this manner: async function bar() { // acquire an axe somehow ... const sword = await foo ...

The error message "TypeError: Attempting to access the 'map' property of an undefined value (React JS)" was displayed

I'm currently working on a recursive function that needs to iterate over an object type called ItemType. However, I encountered an error message: TypeError: Cannot read property 'map' of undefined This is the code snippet causing the issue: ...

The compatibility issue arises when using Material UI Portal with TypeScript, specifically with the 'children' property types

When rendering a component using Material-UI Portal that includes several Material UI buttons, the following code is used: <Portal container={this.myContainer}> <Button onClick={this.handleClick}>Do something</Button> //other but ...

Typescript feature allowing for the return of objects that adhere to a specified interface using wildcard return types

Within my coding framework, I have developed the following interface within an abstract base class: interface MyInterface { field1: string } abstract class BaseClass { // some fields here... abstract serialize(): Array<MyInterface> } As I ...

Implementing Bootstrap 5 JS within an Angular 11 component TypeScript

I am currently working on a project that utilizes Angular 11 and we are aiming to integrate Bootstrap 5 native JS without relying on third-party libraries like ng-bootstrap, MDB, or ngx-bootstrap (jQuery is not being used as well). I understand that using ...

I'm looking to receive the specific data types for express request arguments. How can I

Currently, I am working on incorporating authentication into an express application using passport and typescript. For defining the user model, I have utilized typegoose. Once the login request passes through the passport strategy, a login method is called ...

The perplexing error I'm encountering with Node Vue Typescript during the npm run serve command is providing no

Working on a Node / Vue / Vuetify project in Webstorm was going smoothly until I decided to install vueldiate and lodash. However, upon running npm run serve, I encountered an error message that left me completely baffled: vue-cli-service serve INFO Sta ...

Updating the state in a different component using React and Typescript

The Stackblitz example can be found here I'm attempting to update the useState in one component from another component. Although it seems to work here, it's not functioning properly in my actual application. Here is a snippet of the app.tsx co ...