我有以下内容:
const fff = async (req: express.Request, res: express.Response): Promise<void> => {...}
如何声明
req.body.xxx
存在?这样当我输入 req.body.xxx
时,它会知道它存在于 req.body
对象中吗?我有以下内容:
const fff = async (req: express.Request, res: express.Response): Promise<void> => {...}
req.body.xxx
存在?这样当我输入 req.body.xxx
时,它会知道它存在于 req.body
对象中吗?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
}
基于TypeScript定义,这个的正确语法是:
interface Request<
P = core.ParamsDictionary,
ResBody = any,
ReqBody = any,
ReqQuery = core.Query,
Locals extends Record<string, any> = Record<string, any>
> extends core.Request<P, ResBody, ReqBody, ReqQuery, Locals> {}
以下是从上面提取的代码片段,我们在括号内指定请求类型。
interface ILoginBody {
username: string;
password: number;
}
const fff = async (req: Request<any, Response, ILoginBody>, res: Response): Promise<void> => {
const { username, password } = req.body;
}
Request
对象。我想要扩展req.body
。 - T THE R