Issue
I am using passportjs middleware for authentication in an express/nodejs application. I am getting errors about properties on my request.user object despite having followed the steps for Declaration Merging.
I have created a file at /types/index.d.ts in my project root, and added the following to my tsconfig.json
"typeRoots": [
"/types/index.ts", "node_modules/@types"
]
My global declaration merge looks like this:
import { User } from "../users/user.interface";
declare global {
namespace Express {
export interface Request {
user: User;
}
}
}
** UPDATE **
I have gotten the req.user
object to stop throwing errors by changing my Declaration Merge to a Module Augmentation like so:
import { User } from "../users/user.interface";
declare module "express-serve-static-core" {
interface Request {
user: User;
}
}
When referencing request.session
object I get the following error: Property 'session' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.
Shouldn’t passport’s @types/passport types be merging with express’s request object to add a session?
Does anyone know how I can successfully squash these errors / get TS to recognize this Declaration Merge. I’m new to typescript and have been able to solve most of the issues I have come across but this one just keeps on surfacing.
Solution
To extend the User
type used by Passport, you would merge your declarations into global.Express.User
:
declare global {
namespace Express {
interface User {
/* declare your properties here */
}
}
}
The type definitions provided by @types/passport
do not define global.Express.Request#session
, that is defined by @types/express-session
here.