To fix the "Typescript Error: Property ‘user’ does not exist on type ‘Request’" error with Express, we can add our own definition for the request type.
For instance, we add
IGetUserAuthInfoRequest.ts
import { Request } from "express";
export interface IGetUserAuthInfoRequest extends Request {
user: string;
}
into a TypeScript type definition file.
We create the IGetUserAuthInfoRequest
interface the extends the Request
interface by adding the user
field.
Then we use it by writing
import { Response } from "express";
import { IGetUserAuthInfoRequest } from "./IGetUserAuthInfoRequest";
app.get(
"/auth/userInfo",
validateUser,
(req: IGetUserAuthInfoRequest, res: Response) => {
res.status(200).json(req.user);
}
);
to import IGetUserAuthInfoRequest
and use it as the type for the req
parameter instead of Request
.