TypeScript Inference guide with Mapped Types and Conditional Properties in an Express Middleware
Quick question that's been bugging me - I'm currently working on an Express.js middleware in TypeScript that processes incoming requests. I want to create a mapped type that transforms the request object based on the presence of certain query parameters. The scenario I'm working with is that TypeScript isn't inferring the types correctly when I apply conditional properties based on these query parameters. Hereβs a simplified version of what I've tried: ```typescript import { Request, Response, NextFunction } from 'express'; type QueryParams = { filter?: string; limit?: string; }; type TransformedRequest<T> = T extends { filter: infer F } ? { filter: F; } : {}; type CustomRequest = Request<{}, {}, {}, QueryParams> & TransformedRequest<QueryParams>; const queryMiddleware = (req: CustomRequest, res: Response, next: NextFunction) => { const { filter, limit } = req.query; if (filter) { // Here, TypeScript should know filter is a string, but it throws an behavior. console.log(`Filtering by: ${filter}`); } if (limit) { // This also throws an behavior because TypeScript sees limit as possibly undefined. console.log(`Limit set to: ${limit}`); } next(); }; ``` When I attempt to access `filter` and `limit`, I get the behavior: `Property 'filter' does not exist on type 'CustomRequest'.` It seems like TypeScript isn't recognizing the conditional types correctly. I've tried using `as` assertions in various places to force TypeScript to understand the shape of my request object, but that hasn't resolved the scenario either. I also experimented with using `Partial` and other utility types, but nothing seems to work as expected. Is there a better way to achieve the desired type inference for my transformed request without running into these type errors? Any insights or alternative approaches would be greatly appreciated! How would you solve this?