我把这个作为我的代码:
import jwt from 'jsonwebtoken';
import { Request, Response } from 'express';
import { JWT_EXPIRY, JWT_SECRET } from '../../config';
interface UserParams {
username: string,
password: string
}
interface ReqWithUserParams extends Request {
user: UserParams
}
const createAuthToken = (user: UserParams): string => {
return jwt.sign({ user }, JWT_SECRET, {
subject: user?.username,
expiresIn: JWT_EXPIRY,
algorithm: 'HS256'
});
};
export const login = (req: ReqWithUserParams, res: Response) => {
const authToken = req.user && createAuthToken(req.user);
if (authToken) {
res.json({ authToken });
} else {
res.status(401).json({ message: 'Unauthorized' });
}
};
export const refresh = (req: ReqWithUserParams, res: Response) => {
const authToken = req.user && createAuthToken(req.user);
if (authToken) {
res.json({ authToken });
} else {
res.status(401).json({ message: 'Unauthorized' });
}
};
VSCode中没有类型错误,但是当我运行它时,我得到以下错误:
The last overload gave the following error.
Argument of type '(req: ReqWithUserParams, res: Response) => void' is not assignable to parameter of type 'RequestHandlerParams<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.
Type '(req: ReqWithUserParams, res: Response) => void' is not assignable to type 'RequestHandler<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.
Types of parameters 'req' and 'req' are incompatible.
Type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>' is not assignable to type 'ReqWithUserParams'.
Types of property 'user' are incompatible.
Type 'User | undefined' is not assignable to type 'UserParams'.
Type 'undefined' is not assignable to type 'UserParams'.
我如何解决这个问题,为什么会发生这种情况?我假设扩展请求将允许它是可分配的,因为ParamsDictionary
的类型看起来就是{ [key:string]: any }
1条答案
按热度按时间sauutmhj1#
我查错档案了。事实证明,这是追溯到一个不同的函数,我纠正了这个函数,然后就可以消除这个错误了。把这个留着以防其他人也有同样的经历。只是要确保你不像我一样忽略文件路径!