In a Node.js Express TypeScript project I have such route controller:
<code>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;
...
</code>
<code>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;
...
</code>
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:
const searchQuery = req.body.searchQuery;
, still strict ‘string’ type.const searchQuery = req.body.searchQuery;
, still strict ‘string’ type.const searchQuery: string | undefined = req.body.searchQuery;
, still strict ‘string’ type.
1