Utilizing Express, I have set specific fields on the request
object to leverage a TypeScript feature. To achieve this, I created a custom interface that extends Express's Request
and includes the additional fields.
These fields are initialized at the start of each request and will never have a null value. Therefore, I prefer not to mark them as optional since the values will always be present.
import { type Request } from 'express'
import { type Context } from '../classes/context.class'
export interface CustomReq extends Request {
ctx?: Context
}
app.use((req: CustomReq, res: Response, _: NextFunction) => {
// ...:
});
However, if I designate ctx
as required, TypeScript throws the following error:
No overload matches this call.
The last overload gave the following error.
Argument of type '(req: CustomReq, _: Response, next: NextFunction) => void' is not assignable to parameter of type 'PathParams'.
On the other hand, if it's optional and I try to access req.ctx.someField
, TypeScript warns that ctx
might be undefined. In such cases, I find myself needing to use req.ctx as Context
consistently. Is there an alternative solution that avoids this repeated workaround?