我正在尝试为我的(nodejs)控制器函数创建类型,如下所示
export const registerUser = asyncWrap(async function(req:Request, res:Response, next:NextFunction) {
res.status(200).json({ success: true});
})
并且上面的代码很好,但是我想创建一个类型,所以我可以停止为函数params提供类型,这有点多余
我尝试过的事情
type NormTyped = (fn:Promise<any>) => (req: Request, res: Response, next: NextFunction) => any;
export const registerUser:NormTyped = asyncWrap(async function(req, res, next) {
res.status(200).json({ success: true});
})
但是它给我错误
Type '(...args: any) => Promise<any>' is not assignable to type 'NormTyped'.
Type 'Promise<any>' is not assignable to type '(req: Request<ParamsDictionary, any, any, ParsedQs>, res: Response<any>, next: NextFunction) => any'.
Type 'Promise<any>' provides no match for the signature '(req: Request<ParamsDictionary, any, any, ParsedQs>, res: Response<any>, next: NextFunction): any'.
这是我的asyncWrap的样子(以防万一)
const asyncWrap = (fn: (...args: any) => any) =>
function asyncHandlerWrap(...args: any){
const fnReturn = fn(...args)
const next = args[args.length-1]
return Promise.resolve(fnReturn).catch(next)
}
[NormTyped
应该是接受函数作为参数的函数。
type NormTyped = (fn: (req: Request, res: Response, next: NextFunction) => any) => Promise<any>;
const asyncWrap = (fn: (...args: any) => any) =>
function asyncHandlerWrap(...args: any){
const fnReturn = fn(...args)
const next = args[args.length-1]
return Promise.resolve(fnReturn).catch(next)
}
export const registerUser: NormTyped = asyncWrap(async function(req: string, res, next) {
res.status(200).json({ success: true});
})