NodeJS 输入请求时出错- Express JS - TypeScript

ijnw1ujt  于 5个月前  发布在  Node.js
关注(0)|答案(1)|浏览(65)

我想输入一个RequestList,这样req.params和req.body的类型就像这个接口一样

interface UpdateNoteParams {
    noteId: string,
}

interface UpdateNoteBody {
    title?: string,
    text?: string,
}

字符串
我这样做

export const updateNote : RequestHandler<UpdateNoteParams, unknown, UpdateNoteBody, unknown> = async (req: Request, res: Response, next: NextFunction)


但我得到了这个错误:

Type '(req: Request, res: Response, next: NextFunction) => Promise<void>' is not assignable to type 'RequestHandler<UpdateNoteParams, unknown, UpdateNoteBody, unknown, Record<string, any>>'.
  Types of parameters 'req' and 'req' are incompatible.
    Type 'Request<UpdateNoteParams, unknown, UpdateNoteBody, unknown, Record<string, any>>' is not assignable to type 'Request<ParamsDictionary, any, any, ParsedQs, Record<string, any>>'.
      Types of property 'params' are incompatible.
        Type 'UpdateNoteParams' is not assignable to type 'ParamsDictionary'.
          Index signature for type 'string' is missing in type 'UpdateNoteParams'.ts(2322)


我不知道我是否需要扩展ParamsDictionary或类似的东西,我搜索了很多,但我没有得到如何正确键入请求的答案
提前感谢!!

rqcrx0a6

rqcrx0a61#

你就快成功了,我相信这应该行得通:

export const updateNote: RequestHandler<UpdateNoteParams, unknown, UpdateNoteBody, unknown> = async (
  req: Request<UpdateNoteParams, unknown, UpdateNoteBody, unknown>,
  res: Response,
  _next: NextFunction
) => {
  // Now you can use req.params and req.body with the specified types
  const { noteId } = req.params;
  const { title, text } = req.body;

  // ... business logic

  res.status(200).send('Note updated successfully');
};

字符串

相关问题