Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

why request.query is not 'any' anymore? express request.query typescript error

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

like image 781
dang Avatar asked Apr 19 '20 13:04

dang


People also ask

How to modify a query in express request?

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:

What is the difference between request and reqquery?

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> {}

Can I override a query type in typescript?

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.

Is the type 'request' generic?

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".


1 Answers

This makes express more strict in typings. You have to add types.

const shopEventId: string = req.query.shopEventId as string
like image 71
marcellsimon Avatar answered Oct 17 '22 22:10

marcellsimon