DEV Community

Angela Pat.
Angela Pat.

Posted on

Object literals with satisfies operator for UI field mapping

Our Frontend is responsible for converting fields into labels that make more sense to users.

So far I have seen the use of Enums to solve that purpose but we can also use Objects literals with satisfies and I believe its more developer friendly, flexible and when compiled, it resembles JS.

Object literals: Meant to be used for key-value pairs.

Object literals with satisfies: Preserves the exact literal types.

A use case:

Let’s say we have an Artist songs page that can be sorted by either title, album name, duration , and # of plays. Our sorting mechanism, in this case a REST API, allows sorting by any of the fields.

First, I would create a declarative sort dropdown component where the keys match the API fields and the values offer user-friendly labels

Solution with Object literal

const artistSongSortOptions = {
  title: 'Title',
  albumName: 'Album name',
  duration: 'Duration',
  numberOfPlays: 'Number of Plays',
} as const satisfies Record<string, string>
// We make object read-only by using as const

// Create type from artistSongSortOptions keys
type ArtistSongSortBy = keyof typeof artistSongSortOptions;
Enter fullscreen mode Exit fullscreen mode

πŸ•΅οΈβ€β™€οΈ Hover over that new created type

title, albumName, duration, numberOfPlays

Nice. Object literals are just brilliant ✨

With this approach you can easily complete the following:

  • Display a list of available options, coming from Object.keys(artistSongSortOptions)
  • When an option is selected by the user, you can show the user-friendly text by accessing artistSongSortOptions[selectedOption]
  • Fetch API with sortBy of a type ArtistSongSortBy

A later use case:

Time passes, and you need to display a new page for multiple artists; an API allows sorting only by one of the valid fields: title, albumName, duration, numberOfPlays, and a new field artistName (it's a list of artists, we would like to sort by artist name as well πŸ˜‰)

I would simply use again object literals

const multiArtistSongSortOptions = {
  ...artistSongSortOptions,
  artistName: 'Artist name',
} as const satisfies Record<string, string>
// We make object read-only by using as const
// Create type from artistSongSortOptions keys
type MultiArtistSongSortBy = keyof typeof multiArtistSongSortOptions

Enter fullscreen mode Exit fullscreen mode

πŸ•΅οΈβ€β™€οΈ Hover over that new created type
title, albumName, duration, numberOfPlays and, artist name

Advantages of developing this way

  • Single source of truth: Automatic type updates
  • Type safety
  • Simple HTML generation
  • Consistency with API

Another way is to use Enums, however I consider the use of object literal more intuitive. If you still prefer Enums and want to use them for field mappings, I would recommend using ESLint, check out this post.

Top comments (0)