Lets assume we got the following model
export interface UserModel {
usename: string;
password: string;
email: string;
address: string;
phoneNumber: string
}
The address is optional and the user doesn’t add any so the value of it is null or empty string.
In cases where the value is null, empty string o even undefined for any possible reason i would like to ignore
address
property from the object.
What is the best way to ignore any properties with unwanted values keeping my code strongly typed ?
PS: 1. Adding an external library to clean the unwanted values is not my goal.
2. Correlated service is a POST
method and expecting a UseModel type.
the following is what i tried
function cleanUserModel(user: UserModel): UserModel {
const cleanedUser: Partial<UserModel> = { ...user };
Object.keys(cleanedUser).forEach(key => {
const value = cleanedUser[key as keyof UserModel];
if (value === null || value === '' || value === undefined) {
delete cleanedUser[key as keyof UserModel];
}
});
return cleanedUser as UserModel;
}
Works fine. BUt wondering if there is a cleaner way, with the same result!