JS Built-ins
TypeScriptintermediate

Interface β€” Optional Chaining Display Name

πŸ“– Usage Example
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.

Optional Properties & Nullish Coalescing

Challenge: Implement getUserDisplayName(user) following this priority:

  1. nickname if present
  2. firstName + ' ' + lastName if lastName exists
  3. firstName alone
getUserDisplayName({ firstName: 'Alice', lastName: 'Smith' })  // β†’ 'Alice Smith'
getUserDisplayName({ firstName: 'Bob' })                       // β†’ 'Bob'
getUserDisplayName({ firstName: 'Carol', nickname: 'Caz' })   // β†’ 'Caz'
πŸ’‘ Hints (1)
  • β€’ ?? only falls back on null/undefined, not empty string.