Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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 });
};

>Solution :

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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> => {
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading