Home > Mobile >  Is there a way to specify function type with an arrow function?
Is there a way to specify function type with an arrow function?

Time:02-01

Im using express and i know you can do the following to set teh type of the reques handler.

router.get("/", <RequestHandler> function (req, res, next) {
  //Manage request here
});

Is there a way to do the same with arrow functions? I know I can just specify the type of each param but thats a bit verbose I think.

I know this works

router.get("/", (req: Request, res: Response, next: NextFunction) => {
  //Manage request here
});

But could something like this work?

router.get("/", <RequestHandler>(req, res, next) => {
  //Manage request here
});

I get the following error for every parameter.

Parameter 'req' implicitly has an 'any' type.

CodePudding user response:

With an arrow function, you must surround the whole function expression in parentheses to avoid syntactical issues.

router.get("/", <RequestHandler>((req, res, next) => {
  //Manage request here
}));

Another option with as

router.get(
  "/",
  ((req, res, next) => {
  //Manage request here
  }) as RequestHandler
)

Another option, declare the callback as a standalone variable beforehand, avoiding type assertions entirely

const callback: RequestHandler = (req, res, next) => {
  //Manage request here
} as RequestHandler;

router.get("/", RequestHandler);

CodePudding user response:

If you are on Typescript 4.9 , you could make use of the satisfies keyword:

interface AddFunc {
    (a: number, b: number): number;
}

const add = ((a, b) => {
    return a   b
}) satisfies AddFunc;

CodePudding user response:

Try doing this: <RequestHandler<{type1; type2; type3}>> Or you can create a separate interface

  • Related