node.js - 输入 RequestHandler 时出错 - Express JS - TypeScript
我想编写一个 RequestHandler,这样 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 或类似的东西,我搜索了很多,但没有找到如何正确为 RequestHandler 输入类型的答案
提前谢谢你!!
答案#1
你差不多快成功了,我相信这个应该可行:
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');
};
