Daniel Diekmeier
Daniel Diekmeier

Reputation: 3434

How to declare the type of a default exported function

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:

Upvotes: 2

Views: 1130

Answers (1)

Daniel Diekmeier
Daniel Diekmeier

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

Related Questions