Reputation: 319
I am trying to create a type for my (nodejs)controller function like below
export const registerUser = asyncWrap(async function(req:Request, res:Response, next:NextFunction) {
res.status(200).json({ success: true});
})
and the above code is fine, but I want to create a type so I can stop giving the type for the function params which is kinda redundant
What I've tried
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});
})
But it gives me errors
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'.
This is how my asyncWrap looks like(in-case)
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)
}
Upvotes: 1
Views: 153
Reputation: 319
Seem like typescript chooses to display the type of the one that defined in the function itself if provided so I ending up by defining the type directly in the asyncWrap like below
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)
}
Upvotes: 1
Reputation: 1022
NormTyped
should be a function which accepts a function as an argument.
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});
})
Upvotes: 0