3

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?

2 Answers 2

2

'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) {...}
Sign up to request clarification or add additional context in comments.

1 Comment

Wow, I never knew you could use underscores to bypass the lint rules. Exactly what I'm looking for. Also, now that I know what to search for, here's what I needed: stackoverflow.com/questions/38835001/…
1

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.

1 Comment

Didn't notice the post. It's not a good way to solve the problem, but an interesting one. This is not empty object but destructuring syntax. It will make the function a bit less efficient and would fail in case the first arg is not an object, but is acceptable in this case. The benefit is that doesn't require to invent unique names for params that won't be used.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.