Enhancing User Type Functionality with Passport.js

I am currently working on implementing correct User typing with passport.js.

Within the Express namespace, Passport defines the User interface as an empty interface. You can view the details here: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/22f314360cf1f8c273e9985748519cb07984dc79/types/passport/index.d.ts#L20

By default, code like the example below will result in the error "Property 'id' does not exist on type 'User'":

passport.serializeUser(function(user, cb) {
  process.nextTick(function() {
    cb(null, user.id);
  });
});

This error is expected.

To resolve this issue, I utilized type merging by creating a .d.ts file with the following content:

// express_augmentation.d.ts

declare namespace Express {
  interface User {
    id: string
  }
}

This solution worked well for me.

However, if you prefer to use your own User class that includes an id property and potentially other properties, you may consider the following approach:

// express_augmentation.d.ts

declare namespace Express {
  import MyUser from '../models/user';
  interface User extends MyUser {}
}

Unfortunately, this method did not yield the desired outcome for me. I'm unsure about what I might be missing. Any suggestions?

Answer №1

It turns out that the import failed, even though neither tsc nor VSCode pointed out the issue.

Here's the solution that worked:

declare namespace Express {
  type MyUser = import('../models/user').default;
  interface User extends MyUser {}
}

Interestingly, using

import MyUser from '../models/user';
didn't work as expected in this context. I'm not very familiar with the ... = import(...).default syntax, so I'll have to look into it further.

Ultimately, the code can be simplified to:

declare namespace Express {
  type User =  import('../models/user').default;
}

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

Everything seemed to be going smoothly with my page, until out of nowhere I encountered an error while trying to compile

click here for image description Compilation Errors: ERROR in ./node_modules/body-parser/lib/read.js 20:11-26 Module 'zlib' not found in 'D:\BooksGalore app\frontend\node_modules\body-parser\lib' BREAKING CHA ...

Adding custom CSS and JavaScript to an Angular 4 project can be done by including the necessary

When working with Angular 2, I was able to include stylesheets directly in the index.html like so: <link rel="stylesheet" href="css/mycss.css"> However, with Angular 4, the styles need to be added to the angular-cli.json file within the styles and ...

There is no data in the body or query of the Express request

I have gone through numerous posts to troubleshoot my issue, but none of them have resolved it. Here is what I have tried: var cors = require('./cors.js'); app.use(bodyParser.json()); app.use(bodyParser.urlencoded({ extended: true })); I hav ...

Efficiently managing routes by segmenting them into distinct files

My Express app is structured in the standard Express 4 format, with dependencies at the top, followed by app configuration, routes, and finally the listen function. I'm currently working on organizing my routes into categorized files (e.g., routes/au ...

`Warning: The alert function is not working properly in the console error

I am currently working on integrating otp functionality into my Ionic 3 project. I am facing an issue where I am able to receive the otp, but it is not redirecting to the otp receive page due to a specific error. Below is the console error that I am encou ...

fetching data with Contentful and GatsbyJS

I am currently working on fetching data from Contentful using GraphQL within a Gatsby application, and here is my approach: type AllContentfulBlogs = { allContentfulBlogs: { nodes: Array<{ title?: string | null | undefined, ...

What is the best combination of tools to use for web development: express with jade/ejs, along with html5, css

As I delve into learning node.js/express, a question arises about how jade/ejs, html, and css work in harmony. Allow me to share my understanding: The application logic is implemented in node.js/express A portion of this logic/variables is injected into ...

The 'Server' type is not designed to be generic

Out of nowhere, I encountered the following error: TypeScript: ./..\..\node_modules\@types\ws\index.d.ts:328:18 Type 'Server' is not generic. Angular CLI: 13.3.11 Node: 16.13.2 Package Manager: npm 8.1.2 OS: win3 ...

Access to the XMLHttpRequest from the origin http://localhost:3000 has been restricted by the Cross-Origin Resource Sharing (CORS)

I've successfully set up both the front and backend for an app I am currently developing. Now, I need to test the HTTP requests being sent from the front end to the backend while they are running on localhost. Here's the code snippet for sending ...

Node.js encountering issue with printing an array

Here is the code snippet from my routes file: router.get('/chkjson', function(req, res, next) { req.getConnection(function(err,connection){ var ItemArray = []; var myset = []; var query = connection.query('SELEC ...

Guide to successfully sending and receiving data in the subsequent middleware using NodeJs

I have encountered a challenge while attempting to pass data from one middleware to another. The objective is to return the data to the client in the subsequent middleware, but I am facing difficulty catching it within the send.call. What steps should I t ...

I'm looking to switch out the `~` to turn it into a URL for the backend, seeing as `<img alt="" src="~/media/Banner/plane.JPG">` is returning a 404 error

1. Received an HTTP Request and JSON response from the backend localhost:3000 (entered value using wysiwyg) { "Description": "&lt;img alt=&quot;&quot; src=&quot;~/media/Banner/plane.JPG&quot; /&gt;1 test berita&lt ...

Guide on utilizing the send function in Locomotive Js

When working in Locomotive Js, how can I utilize send() within the action of a controller? It seems that only render() is provided by LCM. Could someone please offer guidance on this matter? ...

How to share data between two different components in Angular 6

I have a component called course-detail that fetches data (referred to as course) from my backend application. I want to pass this data to another component named course-play, which is not directly related to the course-detail component. The goal is to dis ...

NodeJS exclusively communicates with the local computer

I recently created a NestJS Server application. NestJs is an Express-based node server that utilizes TypeScript for development. My goal now is to deploy this application on my Raspberry Pi. However, I am facing challenges as the server is only accessible ...

Utilizing a forEach loop in PDF-kit to display images in a side-by-side layout

I have an API that is capable of adding pictures to a PDF after sending a request to the database. I have successfully made it work for one picture, but I am wondering how to display images side by side. Currently, the images are stacked on top of each oth ...

The most effective method for monitoring updates to an array of objects in React

Imagine a scenario where an array of objects is stored in state like the example below: interface CheckItem { label: string; checked: boolean; disabled: boolean; } const [checkboxes, setCheckboxes] = useState<CheckItem[] | undefined>(undefined ...

The error message "Property 'name' does not exist on type 'User'" is encountered

When running this code, I expected my form to display in the browser. However, I encountered an error: Error: src/app/addproducts/addproducts.component.html:18:48 - error TS2339: Property 'price' does not exist on type 'ADDPRODUCTSComponent& ...

What could be the reason for express.static failing to serve my public directory?

My dilemma lies in attempting to serve my public folder. However, I am unsure as to why my express.static line is not functioning properly. Here is the structure of my public folder: public -images ---img1.png ---blah.png -js ---app.js -pages ---index. ...

The template literal expression is being flagged as an "Invalid type" because it includes both string and undefined values, despite my cautious use of

I am facing an issue with a simple component that loops out buttons. During the TypeScript build, I encountered an error when calling this loop: 17:60 Error: Invalid type "string | undefined" of template literal expression. In my JSX return, I ...