Reputation: 3434
I have several express middlewares in my codebase, which are each in their own file. I want to type them all as express.Handler
instead of typing every argument itself.
My files look basically like this:
export default function exampleMiddleware (req, res, next) {
res.send(req.body.helloWorld)
}
But req
, res
and next
are all treated as any
, because TypeScript doesn't know that this function is supposed to be an express.Handler
. What is the correct way to do this?
I do not want to change them to this, because it is so verbose:
import * as express from 'express'
export default function exampleMiddleware (
req: express.Request,
res: express.Response,
next: express.NextFunction
): void {
res.send(req.body.helloWorld)
}
I tried:
declare function exampleMiddleware: express.Handler
, but it says "Overload signatures must all be exported or non-exported"let exampleMiddleware: express.Handler
, but it says "Merged declaration 'exampleMiddleware' cannot include a default export declaration."Upvotes: 2
Views: 1130
Reputation: 3434
If I avoid default exports (like @spender commented), then I can indeed use:
export const exampleMiddleware: express.Handler = function exampleMiddleware (
req,
res,
next
) {
res.send(req.body.helloWorld)
}
Which is good enough for my purposes, I guess.
Upvotes: 1