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?
query.foo
might be undefined and that's true. – Burrstoneif (query.foo) { parseInt(foo, 10) }
This would still resolve inArgument of type 'string | ParsedQs | string[] | ParsedQs[]' is not assignable to parameter of type 'string'. Type 'ParsedQs' is not assignable to type 'string'
– ColcannonparseInt(foo as string, 10)
. – BurrstoneRequest
is a Generic which can be enhanced but I would like to only typerequest.query
and leave everything else likerequest.body
andrequest.params
as is – Colcannonfunction isNumber(num: any): num is number { return Number.isInteger(num); }
. It still returns inType 'ParsedQs & number' is not assignable to type 'string'.
– Colcannonconst foo = typeof query.foo === "string" ? query.foo : "";
After this, foo is guaranteed to be a string and only a string. – Seemly