I am moving my app from js to ts and encountered the following problem:
In my app I use a middleware function to validate requests. It checks stuff like whether req.files.image exists, image type and image size
imageRouter.route('/upload').post(validateUploadImageData, uploadImage)
However, when I move to the next function uploadImage, I notice a typescript error 'req.files' is possibly 'null' or 'undefined'.ts(18049).
I understand why it's happening: ts doesn't know anything about my validations in the other function, it just strictly checks the type in the current function. However, is there a workaround this problem other than doing the same checks and type narrowing in every middleware function?
If anyone else is looking for a more elegant and type-secure solution to this problem, check out Zod: https://zod.dev It's a schema declaration and validation library that is really easy to use and it closes the execution gap problem between typescript and javascript.
Now my code looks like this:
What is does is basically it validates the data I receive from
ApplyFilterQueryShema.parse(req.query). So we don't need to do 100 lines of validation in every function, but at the same time don't compromise data safety