0

I am making a basic API with express, typeORM and JWT

I followed this question to attach my users information to the Request in my middleware and it worked well.

But I decided that keeping only my usersId was not enough so I tried to save the entire User TypeOrm entity, but immediately I got the following error:

Property 'user' does not exist on type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.

So basically I have this extension

import { User } from "../entities/User";

declare namespace Express {
    export interface Request {
        user: User;
    }
}

when I use it I get the following error enter image description here

To me this makes absolutely no sense to me, because when I change it to this:

declare namespace Express {
    export interface Request {
        user: string;
    }
}

it works perfectly fine

enter image description here

Could there be a hidden error that I am missing? could this be a bug at the frameworks level?

Thank you!

Lin Du
  • 88,126
  • 95
  • 281
  • 483
Daniel Cruz
  • 1,437
  • 3
  • 5
  • 19

1 Answers1

0

Try:

import { Request, Response } from 'express';

class User {
  name: string = '';
}

declare module 'express' {
  export interface Request {
    user: User;
  }
}

function controller(req: Request, res: Response) {
  const newUser = new User();
  req.user = newUser;
}

package version:

"express": "^4.17.1",
"@types/express": "^4.17.11"
Lin Du
  • 88,126
  • 95
  • 281
  • 483