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