Alexander Mills
Alexander Mills

Reputation: 100020

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

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?

Upvotes: 31

Views: 23868

Answers (3)

nezort11
nezort11

Reputation: 635

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

Upvotes: 0

cbdeveloper
cbdeveloper

Reputation: 31365

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

Upvotes: 17

Carloluis
Carloluis

Reputation: 4320

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

import { RequestHandler } from 'express';

Upvotes: 55

Related Questions