Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to cast req.query parameters in Express using Typescript

I'm running an express.js application using TypeScript. Every time I try to process request.query.foo I get the following error:

Argument of type 'string | ParsedQs | string[] | ParsedQs[] | undefined' is not assignable to parameter of type 'string'.

Setup:

import { Request, Response } from 'express';

function bar(request: Request, response: Response) {
  const foo: string = request.query.foo; //marked as error
}

I read on the documentation of Express that you can set a configuration called "query parser" that when set to "simple" will always parse the query parameters as a string

The problem is that Typescript still thinks that something other than string or undefined may come and I can't seem to find a way to override the Request interface, I can only extend it.

Is there any way to override the Request interface? is there something wrong in my approach?

like image 657
Miguel Alejandro Smurawski Avatar asked Nov 06 '22 04:11

Miguel Alejandro Smurawski


2 Answers

Late to the party and not the bes but you can try

const name: string = req.query.name as string;

just fail save the code by null check

like image 22
Aaron Aguilar Avatar answered Nov 12 '22 13:11

Aaron Aguilar


You could define the types that you will expect on the ReqBody, ReqQuery and the other generics of Request type. For the Response you should also be able to define other types and pass it as generics. Don't forget to install @types/express by running npm install -D @types/express

Then you could create other SomeHandlerRequest and others ReqDictionary, ReqBody, ReqQuery and ResBody for each specific case.

import { Request } from 'express'

// if you need define other response generics
// import { Request, Response } from 'express'


// This types could be exported from other file. Then you should import them
type ReqDictionary = {}
type ReqBody = { foo1 ?: string }
type ReqQuery = { foo2 ?: string }
type ResBody = { foo3 ?: string }

type SomeHandlerRequest = Request<ReqDictionary, ResBody, ReqBody, ReqQuery>

const myCustomHandler = (req: SomeHandlerRequest, res) : void => {
   const { foo1 } = req.body
   const { foo2  } = req.query

   // Your custom logic ..... for example...
   if (foo1) {
      console.log("foo1 value = ", foo1)
   }
   if (foo2) {
      console.log("foo2 value = ", foo2)
   }

   res.status(200).json({ foo3 : "it works" })
}

like image 150
Helmer Barcos Avatar answered Nov 12 '22 13:11

Helmer Barcos