DEV Community

loading...

Discussion on: Indexing objects in TypeScript

Collapse
pierreyveslebrun profile image
Pierre Lebrun

Just sharing my personal trick, which is a bit off topic and hacky.

I usually prefer to handle such edge cases within the objet literal itself, by providing a default key.

Then I basically lie to the TypeScript compiler by omitting the extra default key in my type definitions.


interface Status {
  online: 'Online',
  offline: 'Offline',
  busy: 'Busy',
  dnd: 'Do Not Disturb',
}

function getDisplayedStatus(status: keyof Status) {
  const statusDisplays = {
    online: 'Online',
    offline: 'Offline',
    busy: 'Busy',
    dnd: 'Do Not Disturb',
    default: 'Unknown'
  }

  return statusDisplays[status] || status.default
}

  const displayedStatus = getDisplayedStatus(status as keyof Status)