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
Solution 1:
I was stuck on the same problem earlier. Here is how I solved it.
- I created a separate directory called @types in my project for declaration merging to work.
- 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>
}
}
}
- 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:
- Create a types folder in your src directory
- Create a folder within the types folder with the name of the package you intend to extend. (In this case express).
- Create an index.d.ts file in that folder
src/
- types/
- express/
- index.d.ts
- add this code to the index file
import express from "express";
declare global {
namespace Express {
interface Request {
user?: Record<string,any>
}
}
}
- remember to update your tsconfig.json file
{
"compilerOptions": {
"typeRoots" : ["./src/types", "./node_modules/@types"]
}
}
This should work