我正在尝试为我的(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)
}
答案 0 :(得分:1)
好像打字稿会选择显示在函数本身中定义的那个的类型(如果提供的话),所以我最终通过直接在asyncWrap中定义类型来结束,如下所示
const asyncWrap = (fn: (req: Request,res: Response,next: NextFunction) => Promise<any>) =>
function asyncHandlerWrap(req: Request,res: Response,next: NextFunction){
const fnReturn = fn(req,res,next)
return Promise.resolve(fnReturn).catch(next)
}
答案 1 :(得分:0)
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, res, next) {
res.status(200).json({ success: true});
})