使用Joi验证API的req.body时遇TypeScript错误:Property does not exist on type
解决Joi验证req.body时的“Property does not exist on type”错误
问题根源
- Joi返回属性名不匹配:Joi的
validate方法返回的对象固定包含error和value属性,你代码里用的err和val是不存在的属性,TypeScript无法识别,直接触发类型错误。 - req.body类型未明确:Express默认的
Request类型没有定义body的具体结构,TypeScript无法推断req.body的字段,也会引发类型检查报错。
修复方案
1. 修正Joi验证的解构属性名
将错误的解构变量名替换为Joi标准返回属性,或者通过别名映射保持你原来的变量名:
// 方式1:用Joi标准属性名 const { error, value } = updatedBioScheme.validate(req.body); // 方式2:用别名映射保留原变量名 const { error: err, value: val } = updatedBioScheme.validate(req.body);
2. 定义req.body的类型接口
为req.body声明明确的类型,让TypeScript识别其结构:
interface UpdateBioRequestBody { bio: string; }
然后在函数参数中指定req的类型为Request<{}, {}, UpdateBioRequestBody>(三个泛型分别对应params、query、body的类型)。
完整修复后的代码
import { Request, Response } from 'express'; import Joi from 'joi'; import { myContainer, TYPES } from '../your-container-path'; import { ProfileServicesRepository } from '../your-repo-path'; // 声明请求body的类型结构 interface UpdateBioRequestBody { bio: string; } const idScheme = Joi.string().required(); const updatedBioScheme = Joi.object({ bio: Joi.string() .min(3) .required(), }); export async function updatedBio(req: Request<{}, {}, UpdateBioRequestBody>, res: Response) { try { const uid = req.query.uid; // 修正Joi返回值的解构 const { error: err, value: val } = updatedBioScheme.validate(req.body); const { error, value } = idScheme.validate(uid); if (error) { res.status(400).json({ error: "Invalid uid parameter" }); return; } else if (err) { return res.status(400).json(err); } const userId = value; const { bio } = val; const inject = myContainer.get<ProfileServicesRepository>(TYPES.ProfileServices); const data = await inject.updateBio(userId, bio); if (data == undefined) { return res.status(400).json({ error: "User not available yet!!" }); } return res.status(200).json({ data, message: "Successful" }); } catch (error) { return res.status(400).send({ error, message: "error" }); } }
额外提示
- 若不想定义接口,可临时用类型断言绕过检查:
updatedBioScheme.validate(req.body as { bio: string }),但推荐用接口的方式,更符合TypeScript类型规范。 - 代码中
Sucessful是拼写错误,建议修正为Successful。
内容的提问来源于stack exchange,提问作者Gbenga B Ayannuga
相关产品推荐
相关产品推荐

