Is there a type in @types/express for Express middleware functions
Asked Answered
I

3

30

Right now I have this in a custom .d.ts file:

import { Request, Response, NextFunction } from 'express';
export type MiddleWareFn = (req: Request, res: Response, next: NextFunction) => void;

and I reference that file like so:

router.use('/foo', <MiddleWareFn> function(req,res,next){});

however I am wondering if Express has typings for middleware functions already?

Iodometry answered 28/2, 2018 at 2:10 Comment(0)
B
16

Here is how I'm handling it:

import type { RequestHandler } from "express";

export const myMiddleware: RequestHandler = (req, res, next) => {
  // HANDLE REQUEST
  // RESPOND OR CALL NEXT()
};
Blackfish answered 6/1, 2021 at 10:51 Comment(0)
S
53

Yes. You need to import also RequestHandler. Check definition here

import { RequestHandler } from 'express';
Shakedown answered 28/2, 2018 at 2:25 Comment(1)
ok. feel free to mark this as the answer of your question. cheers!Shakedown
B
16

Here is how I'm handling it:

import type { RequestHandler } from "express";

export const myMiddleware: RequestHandler = (req, res, next) => {
  // HANDLE REQUEST
  // RESPOND OR CALL NEXT()
};
Blackfish answered 6/1, 2021 at 10:51 Comment(0)
D
0

I am using RequestHandler as follows:

import type { RequestHandler } from "express";

type ArgumentTypes<T> = T extends (...args: infer P) => any ? P : never;

type RequestHandlerArgs = ArgumentTypes<RequestHandler>;

app.use((...args: RequestHandlerArgs) => {
  const [req, res, next] = args;
  // ...
});
Douglassdougy answered 12/9, 2023 at 21:54 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.