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 });
};
CodePudding user response:
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> => {