node.js – Request body types are not optional

In a Node.js Express TypeScript project I have such route controller:

import type { Request } from 'express';

export type TGetItemsControllerRequest = Request<
  unknown,
  unknown,
  {
    page: number;
    limit: number;
    searchQuery?: string;
  }
>;

export const getItemsController = async (
  req: TGetItemsControllerRequest,
  res: TGetItemsControllerResponse,
) => {
  const { limit, page, searchQuery } = req.body;
  ...

For some reasons searchQuery from the destructuring has a strict string type, although I expect string | undefined. How to enforce optional type for the req.body.searchQuery?

I’ve tried to use:

  1. const searchQuery = req.body.searchQuery;, still strict ‘string’ type.
  2. const searchQuery = req.body.searchQuery;, still strict ‘string’ type.
  3. const searchQuery: string | undefined = req.body.searchQuery;, still strict ‘string’ type.

Read more here: Source link