interface Profile { displayName?: string; username: string }
function getName(p: Profile): string {
return p.displayName ?? p.username
}The nullish coalescing operator (??) provides a fallback when an optional property is undefined.
Challenge: Implement getUserDisplayName(user) following this priority:
nickname if presentfirstName + ' ' + lastName if lastName existsfirstName alonegetUserDisplayName({ firstName: 'Alice', lastName: 'Smith' }) // β 'Alice Smith'
getUserDisplayName({ firstName: 'Bob' }) // β 'Bob'
getUserDisplayName({ firstName: 'Carol', nickname: 'Caz' }) // β 'Caz'