When I send body data to an endpoint on my Node/Express server, there is no guarantee that the request actually contains all the required fields. Is it, therefore, correct to always declare all body properties as optional types in TypeScript like I did in below example?
interface SignUpBody {
username?: string, // all these properties are declared as optional (? operator)
email?: string,
password?: string,
}
export const signup: RequestHandler<unknown, unknown, SignUpBody, unknown> = async (req, res, next) => {
try {
const username = req.body.username;
const email = req.body.email?.toLowerCase();
const passwordRaw = req.body.password;
if (!username || !email || !passwordRaw) { // optional types force me to check them first
throw createHttpError(400, 'Parameters missing');
}
[...]
}