简体   繁体   English

如何告诉 Passport JS 中的 typescript req.user 永远不会未定义?

[英]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.使用 Passport JS 时,路由中的req.user被视为可能未定义。 But the middleware before my route method is making sure that this isn't the case.但是我的路由方法之前的中间件确保不是这种情况。 How to tell that to typescript?如何告诉 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.在上面的 typescript 中抛出错误,因为 user.id 可能未定义。

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:我建议您使用您需要的参数简单地声明全局 Express 命名空间:

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.之后,您将能够在没有//@ts-ignore或可选链接的情况下使用req.user

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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