我目前正在开发一个使用打字稿的快速应用程序。我目前正在研究身份验证中间件,并且想知道您是否可以通过某种方式使中间件类型安全:
authenticateJwt = (
req: RequestWithToken,
res: Response,
next: () => void
) => {
// Append the decoded req.token to the req header so we can use it internally
const token = req.token;
// @ts-ignore
this.verifyJwt(token)
.then((decoded: Token) => {
req.token = decoded;
next();
})
.catch(() => res.status(401).send('Unauthorized'));
};
现在在我的 routes.ts 中:
router.get(
'/me',
// @ts-ignore
jwtService.authenticateJwt,
userController.getProfileFromUser
);
我必须写 // @ts-ignore 因为它说那'(req: RequestWithToken, res: Response, next: () => void) => void
不是类型RequestHandlerParams
的定义RequestWithToken
:
export interface RequestWithToken extends Request {
token: Token;
}
export interface Token {
username: string;
}