简体   繁体   中英

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

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.

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-ignore or optional chaining.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM