So I have a case where just before I push to my sqlite database I want to clean up the email in my user object. I have a few different functions where i need to do this, like creation of the user and in updates of the user. So considering the case:
export const addUser = (user: CreateUser) => {
db.prepare(sqlInsertUser).run(cleanEmail(user))
}
export const updateUser = (user: UpdateUser) => {
db.prepare(sqlUpdateUser).run(cleanEmail(user))
}
type CreateUser = {
email: string
password: string
permissionLevel?: number
}
type UpdateUser = {
email: string
password: string
}
Now I'm trying to implement:
const cleanEmail = (user: ?) => {
user.email = user.email.trim()
return user
}
But I'm blanking out here, how do i grab both types and return the whole object? What do I put as type?
How can I do this well, even with more types but where all the types contain the email property?
CodePudding user response:
You can take a generic type that must have an email property that is a string:
const cleanEmail = <T extends { email: string }>(user: T) => {
user.email = user.email.trim()
return user // return type is inferred as 'T'
};