Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'

Please help, I am getting this error

src/app/middlewares/authentication.ts:16:17 - error TS2339: Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.

16 req.user = user;

I have created the .d.ts file and also included it in tsconfig file. Still I am not able to run this code

Please find attached screenshots

enter image description here

enter image description here

enter image description here

enter image description here


Solution 1:

I was stuck on the same problem earlier. Here is how I solved it.

  1. I created a separate directory called @types in my project for declaration merging to work.
  2. Next I created a file in it called index.d.ts with following content. Please pay attention that we need to declare our own request within global. Also, importing express is important as well.
import * as express from "express"
declare global {
    namespace Express {
        interface Request {
            user? : Record<string,any>
        }
    }
}
  1. I added the following line under compilerOptions in my tsconfig.json.
 "compilerOptions": {
     ...other settings,
     "typeRoots": ["@types", "node_modules/@types"],
     ...other settings
 }

And that's it. It should works with these changes.

Solution 2:

  1. Create a types folder in your src directory
  2. Create a folder within the types folder with the name of the package you intend to extend. (In this case express).
  3. Create an index.d.ts file in that folder
 src/
   - types/
    - express/
     - index.d.ts
  1. add this code to the index file
import express from "express";

declare global {
  namespace Express {
    interface Request {
      user?: Record<string,any>
    }
  }
}
  1. remember to update your tsconfig.json file
{
  "compilerOptions": {
    "typeRoots" : ["./src/types", "./node_modules/@types"]
  }
}

This should work