I have a question about the code below, I am not sure to understand why the second return is valid. Doesn't the first return do the same kind of check ?
type User = {
email: string
firstName?: string
lastName?: string
first_name?: string
last_name?: string
} & ({ first_name: string } | { firstName: string }) &
({ last_name: string } | { lastName: string })
const formatUserFullName = (firsname: string, lastname: string): string => `${firsname} ${lastname}`
export const computeUserFullName = (member: User): string => {
let { firstName, lastName } = member
if (!firstName) {
firstName = member.first_name
}
if (!lastName) {
lastName = member.last_name
}
// This throw an error about firstName and lastName that can be undefined and are not accepted by my method
return !firstName && !lastName
? member.email
: formatUserFullName(firstName, lastName)
// This works
return !!firstName && !!lastName
? formatUserFullName(firstName, lastName)
: member.email
}
Thanks for your help :)
!!firstName && !!lastNameis!(!!firstName && !!lastName)which simplifies to!firstName || !lastName!firstName && !lastName,firstNamecould be'mark', andlastNamecould be undefined and it would go toformatUserFullName('mark', undefined). Since you've definedformatUserFullNameas taking twostrings, notstring | undefined, it rightfully rejects that.