Lun*_*una 6 javascript node.js express typescript passport.js
当使用 Passport JS 时,req.user路由内部被视为可能未定义。但我的路由方法之前的中间件确保情况并非如此。如何将其告诉打字稿?
Object is possibly 'undefined'.
例子:
someMethod = async (req: Request, res: Response) => {
const { user } = req
const userId: number = user.id
}
Run Code Online (Sandbox Code Playgroud)
在上面的打字稿中抛出错误,因为 user.id 可能未定义。
我当然可以做这样的事情:
if (!user) return
const userId: number = user.id
Run Code Online (Sandbox Code Playgroud)
但我相信通过我的方法一遍又一遍地重复这段代码并不是最好的方法,因为中间件甚至在到达路由方法之前就已经这样做了。
我建议您简单地使用您需要的参数声明全局 Express 命名空间,如下所示:
declare global {
namespace Express {
interface Request {
user: User //or other type you would like to use
}
}
}
Run Code Online (Sandbox Code Playgroud)
之后,您将能够在req.user没有链接//@ts-ignore或可选链接的情况下使用。
someMethod = async (req: Request, res: Response) => {
const { user } = req
const userId: number = user.id //user will be defined
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
2191 次 |
| 最近记录: |