TypeScript报错:JWT解析后类型'string|JwtPayload'不存在_id如何解决
报错根因
这个是TypeScript类型检查触发的报错:jsonwebtoken库的jwt.verify方法默认返回值类型是string | JwtPayload联合类型,只有JwtPayload类型的对象才可能携带你生成Token时写入的自定义_id字段,string类型本身不存在_id属性,因此类型校验不通过。
解决方案
方案1:类型断言(简单高效,推荐)
先定义你生成Token时用到的Payload结构,再将jwt.verify的返回值直接断言为该结构即可:
// 可以提前定义全局通用的自定义JWT载荷类型 interface CustomJwtPayload { _id: string; // 生成Token时写入的其他自定义字段也可在这里补充声明 } const auth = async (req, res, next) => { try { // 注意原代码的replace方法缺少Bearer后的空格,修正避免token前残留空格解析失败 const token = req.header("Authorization").replace("Bearer ", "").trim(); // 断言为自定义的载荷类型 const decoded = jwt.verify(token, "thisisfromabhishek") as CustomJwtPayload; const user = await User.findOne({ _id: decoded._id, "tokens.token": token, }); if (!user) { throw new Error(); } req.token = token; req.user = user; next(); } catch (e) { res.status(401).send({ error: "Please authenticate." }); } };
如果临时调试不想定义类型,也可以直接断言为any,但会丢失类型校验能力,不推荐长期使用:
const decoded = jwt.verify(token, "thisisfromabhishek") as any;
方案2:类型收窄(更安全,适合严格类型校验的项目)
先做类型判断排除string的情况,TypeScript会自动识别后续代码中的decoded为对象类型,不会再报错:
const decoded = jwt.verify(token, "thisisfromabhishek"); // 先排除string类型、以及不存在_id的情况 if (typeof decoded === "string" || !("_id" in decoded)) { throw new Error("Invalid token"); } // 走到此处TypeScript已确认decoded存在_id属性 const user = await User.findOne({ _id: decoded._id, "tokens.token": token, });
注意事项
请确认你生成Token的逻辑中,确实将_id字段写入了签名的载荷中,示例生成逻辑如下:
const token = jwt.sign({ _id: user._id.toString() }, "thisisfromabhishek", { expiresIn: "7d" });
内容的提问来源于stack exchange,提问作者Abhishek Vats
相关产品推荐
相关产品推荐

