In my Express.js application, I have a series of middleware functions. By the design of these functions, if the request reaches a particular point (say, a controller function), it's guaranteed that certain request properties (like req.user) have been set by earlier middleware. However, TypeScript's strict null checks still require me to handle cases where these properties might be null or undefined. I want to avoid using TypeScript's non-null assertion operator (!) excessively, as it feels like bypassing the system rather than using it properly. Additionally, I'd prefer not to insert manual checks for these properties again in my controllers or other middleware since these checks have already been conclusively handled in previous middleware.
Is there a best practice for asserting the presence of object properties in TypeScript when their existence is ensured by the application's logic (such as prior middleware ensuring req.user is defined)? What's a clean, safe way to handle this scenario without littering my code with unnecessary checks or assertions?
Example:
router.get(
'/',
authRequired(), // made sure here that req.user will exists
abc(),
xyz(),
usersControllers.getAllUsers
)
getAllUsers Controller
const getAllUsers = async (req: AuthRequest, res: Response): Promise<Response> => {
const { userId, role } = req.user
AuthRequest:
export interface AuthRequest extends Request {
user?: {
userId: number
role: string
}
}