属性'email'在类型 'string' 上不存在



我是typescrypt的新手,目前正在将一个项目从JS迁移到TS。当我在服务器端点上更改一些内容时,出现了一个错误:

Property 'email' does not exist on type 'string | JwtPayload'

这是我迄今为止的代码:

try {
const token = await TokenController.getTokenFromRequest(req);
const decoded = jwt.decode(token);
const user = await AuthController.getUserByMail(decoded.username); // <- Error appears here
res.json(user);
} catch (error: any) {
ErrorController.errorCallback(error, res);
}

编辑:我的"getUserByMail"代码看起来是这样的:

static async getUserByMail(email: string, includePassword = false) {
let query = User.findOne({
email: email
});
if (!includePassword) {
query.select('-password');
}
return query.exec();
}

我知道发生错误是因为我试图访问string没有的属性。有什么建议吗?

创建全局.d.ts:

// global.d.ts
declare module "jsonwebtoken" {
export interface JwtPayload {
//make optional so when you try to decode stuff other than user it will show it can be undefined
email?: string;
}
}

相关内容

最新更新