Categories
JavaScript Answers

How to fix TypeScript Error: Property ‘user’ does not exist on type ‘Request’?

Spread the love

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.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *