Typescript 扩展了 Express 请求主体

T T*_*E R 4 express typescript

我有以下内容:

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

我如何声明它req.body.xxx存在?那么当我输入时req.body.xxx它会知道它存在于该req.body对象上吗?

hoa*_*gdv 5

定义您的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
}
Run Code Online (Sandbox Code Playgroud)

  • 如果 req.body 与 ILoginBody 不匹配,服务器会抛出错误吗? (2认同)