Typescript 扩展了 Express 请求体。

4

我有以下内容:

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

如何声明 req.body.xxx 存在?这样当我输入 req.body.xxx 时,它会知道它存在于 req.body 对象中吗?

1
@ThomasSablik 它扩展了 Request 对象。我想要扩展 req.body - T THE R
2个回答

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
}

1
如果req.body与ILoginBody不匹配,服务器会抛出错误吗? - olawalejuwonm

2

基于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;
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接