Pouria
Pouria

Reputation: 127

How do you handle express controller method parameters when using typescript?

I'm using express for routing and I don't need to use the Request object in my controller method. However, I can't find a simple way to force the exclusion of the Request parameter.

This first example passes typescript validation.

  public async findAll(req: Request, res: Response) {
    // search the db for all transactions
    const transactions = await Transaction.find();

    res.status(200).send({ transactions, incoming: req.body });
  }

This example compiles into valid javascript but doesn't pass typescript validation as I get the error 'req' is declared but its value is never read.

  public async findAll(req: Request, res: Response) {
    // search the db for all transactions
    const transactions = await Transaction.find();

    res.status(200).send({ transactions });
  }

Ideally I don't want to include the Request in my method parameter at all. Is this possible without an intricate workaround?

Upvotes: 3

Views: 1557

Answers (2)

Estus Flask
Estus Flask

Reputation: 222369

'req' is declared but its value is never read error may be caused by TypeScript noUnusedParameters option. If it interferes with development process, it can be disabled in favour of similar TSLint rule which can be fine-tuned to cause a warning instead of an error.

Unused parameters can be conventionally underscored to avoid the check. This is the case for TypeScript:

public async findAll(_req: Request, res: Response) {...}

Upvotes: 2

Pouria
Pouria

Reputation: 127

I just found a solution with some more trial and error. Please post if you can find a more elegant solution.

To avoid the typescript compiler error message, simply make the function parameter an empty object ({}).

The code from the question will now look like

public async findAll({}, res: Response) {
  // search the db for all transactions
  const transactions = await Transaction.find();

  res.status(200).send({ transactions });
}  

Hope this helps someone in the future as I had trouble finding an existing post.

Upvotes: 1

Related Questions