首页 > 解决方案 > Typescript 扩展了 Express Request 正文

问题描述

我有以下内容:

const fff = async (req: express.Request, res: express.Response): Promise<void> => {...}

我如何声明它req.body.xxx存在?所以当我输入req.body.xxx它会知道它存在于req.body对象上?

标签: typescriptexpress

解决方案


定义您的Request类型,该类型扩展express.Request,您可以设置请求正文类型:

interface ILoginBody {
  username: string;
  password: number;
}

interface ILoginRequest extends Request {
  body: ILoginBody;
}

// use ILoginRequest instead of express.Request
const fff = async (req: ILoginRequest, res: Response): Promise<void> => {
  const { username, password } = req.body; // body now is an ILoginBody
}

推荐阅读