To fix TypeScript Error: Property ‘user’ does not exist on type ‘Request’, we add our own interface.
For instance, we weite
import { Request } from "express";
export interface IGetUserAuthInfoRequest extends Request {
user: string;
}
to add the IGetUserAuthInfoRequest
in definitionFile.ts.
IGetUserAuthInfoRequest
inerits from the Request
interface built into Express.
We add the user
property to it.
And then we write
import { Response } from "express";
import { IGetUserAuthInfoRequest } from "./definitionfile";
app.get(
"/auth/userInfo",
validateUser,
(req: IGetUserAuthInfoRequest, res: Response) => {
res.status(200).json(req.user);
}
);
to use it when we divide the type of the req
parameter in the route handler.
We can then use req.user
without errors.