Daniel Cajas
Daniel Cajas

Reputation: 1

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

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.

Upvotes: 0

Views: 109

Answers (3)

Denis Dryagin
Denis Dryagin

Reputation: 21

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

Upvotes: 0

CertainPerformance
CertainPerformance

Reputation: 370729

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

Upvotes: 2

vighnesh153
vighnesh153

Reputation: 5388

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;

Upvotes: 1

Related Questions