简体   繁体   中英

Typescript definitions of nested function

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM