How to tell typescript req.user in Passport JS never will be undefined?

Viewed 1505

When using Passport JS, the req.user inside the route, is treated as possible undefined. But the middleware before my route method is making sure that this isn't the case. How to tell that to typescript?

Object is possibly 'undefined'.

Example:

someMethod = async (req: Request, res: Response) => {
  const { user } = req
  const userId: number = user.id
}

In the above typescript throw an error because user.id is possibly undefined.

I sure could do something like this:

if (!user) return
const userId: number = user.id

But I believe that repeating this piece of code over and over through my methods is not the best approach because middleware is already doing that before even reach the route method.

1 Answers

I suggest you to to simply declare global Express namespace with params that you need like that:

declare global {
  namespace Express {
    interface Request {
      user: User //or other type you would like to use
    }
  }
}

After that you will be able to user req.user without //@ts-ignoreor optional chaining.

someMethod = async (req: Request, res: Response) => {
  const { user } = req
  const userId: number = user.id //user will be defined
}
Related