Pentium3k
Pentium3k

Reputation: 145

Type res.json in express.js to provide default structure of response

I would like to know how to type res.json. I would like to have a default structure of the response, like message and error, but also have the availability to add other data. I mean when I write res. status(200).json({product: foundProduct) I will get an error that I need to provide a message and error.

export const getProduct = async (
  req: Request<{ id: string }, {}, {}>,
  res: Response
): Promise<void> => {
  const productId = req.params.id;
  const foundProduct = await Product.findOne({ _id: productId });
  res
    .status(200)
    .json({ message: "Product found", error: false, product: foundProduct });
};

Upvotes: 0

Views: 60

Answers (1)

Anatoly
Anatoly

Reputation: 22783

You just need to indicate generic parameters in Response type of res parameter:

Response<ResBody = any, Locals extends Record<string, any> = Record<string, any>>
export const getProduct = async (
  req: Request<{ id: string }, {}, {}>,
  res: Response<{ message: string, error: boolean, product: Product }>
): Promise<void> => {

Upvotes: 1

Related Questions