1

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)
}
2
  • What's the type/interface of NextFunction? Commented May 30, 2020 at 20:49
  • @Paul It is from @type/express which is just the type for the next middleware function Commented May 30, 2020 at 20:53

2 Answers 2

1

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)
}
Sign up to request clarification or add additional context in comments.

Comments

0

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});
})

1 Comment

Tried it already, but the ts-linter still say that req, res, next are the type of any and it's not corresponding to the type above that declared

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.