How to type `request.query` in express using TypeScript?
The solution is to use generics in the following manner.
const router = Router();interface Foo { foo: string;}function getHandler(request: Request<{}, {}, {}, Foo>, response: Response) { const { query } = request; query.foo;}router.route('/') .get(getHandler)
I like to use the following approach in my projects.
const { url } = req.query; if (typeof url !== "string") { throw new ServerError("Query param 'url' has to be of type string", 400); }
After checking the type TypeScript won't complain any more for this scope.
Another possible solution is to use Type Assertion:
function getHandler(request: Request, response: Response) { const foo: string = request.query.foo as string //do something with foo ...}