Search code examples
typescriptexpressurltypesrequest

How to type `request.query` 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'.
  Type 'undefined' is not assignable to type 'string'.

Setup:

import { Request, Response, Router } from 'express';

const router = Router();

function getHandler(request: Request, response: Response) {
  const { query } = request;

  query.foo; // string | QueryString.ParsedQs | string[] | QueryString.ParsedQs[] | undefined

}

router.route('/')
  .get(getHandler)

Is there a proper way to type request.query without casting?


Solution

  • Definition

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

    Source: https://github.com/DefinitelyTyped/DefinitelyTyped/blob/89a4f41af507e68daf5f4794ad257f48920275f2/types/express/index.d.ts#L113-L118

    Example

    import type { Request, Response } from 'express';
    
    interface RequestParams {}
    
    interface ResponseBody {}
    
    interface RequestBody {}
    
    interface RequestQuery {
      foo: string;
    }
    
    function getHandler(
      request: Request<RequestParams, ResponseBody, RequestBody, RequestQuery>,
      response: Response
    ) {
      const { query } = request;
    
      query.foo; // string
    }