after npm i this is the error that i get if i try to pass query params to a function that expects string:
Argument of type 'string | Query | (string | Query)[]' is not assignable to parameter of type 'string'.
Type 'Query' is not assignable to type 'string'.ts(2345)
import express from "express";
async function getProductsImagesByShopEvent(req: express.Request, res: express.Response,
next: express.NextFunction) {
try {
const params = req.query;
if (!params || !params.shopEventId)
throw new CustomError("params are missing in /business/getProductsImagesByShopEvent", 400, "params are missing");
const shopEvent = new ShopEvent();
const events = await shopEvent.getProductsImagesByShopEvent(params.shopEventId);
res.json(events);
}
catch (error) {
next(error);
}
}
async getProductsImagesByShopEvent(shopEventId: string) {
}
the error is in params.shopEventId.. if i add: const params = (req.query as any); it works
Modifying the query in Express.Request is somewhat more tricky, because Express uses types from express-serve-static-core , which in turn Express doesn’t expose. So the only way to get hold of the proper types is to import { Query } from 'express-static-serve-core'; . The solution is to do:
The Request is a generic which accepts additional definitions: interface Request< P = core.ParamsDictionary, ResBody = any, ReqBody = any, ReqQuery = core.Query, Locals extends Record<string, any> = Record<string, any> > extends core.Request<P, ResBody, ReqBody, ReqQuery, Locals> {}
Look at e.g. typescriptlang.org/docs/handbook/…. Overriding the query type won't change the runtime behaviour (it can't, types and TS don't exist at runtime). The solution is to use generics in the following manner.
I'm trying to use this approach and getting the error: Type 'Request' is not generic. Tested on @types/express 4.17.11. Works great! BTW, it would be better to use Request<unknown, unknown, unknown, Foo>. Otherwise, the ESLint will give error: Don't use {} as a type. {} actually means "any non-nullish value".
This makes express more strict in typings. You have to add types.
const shopEventId: string = req.query.shopEventId as string
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With