DEV Community

Rense Bakker
Rense Bakker

Posted on • Edited on

1

Mapping Records to arrays

I needed this functionality to parse a configuration regardless of whether it was supplied as an array or a Record. This function converts the Record into an array of the same type:

function mapRecordToArray<T, R extends Omit<T, K>, K extends keyof T>(record: Record<string, R>, recordKeyName: K) {
  return Object.keys(record).map(key => ({ ...record[key as keyof typeof record], [recordKeyName]: key })) as T[]
}
Enter fullscreen mode Exit fullscreen mode

It can be used like this:

type Field = {
  name: string,
  label: string,
}

type Collection = {
  name: string,
  label: string,
  fields: Record<string, Omit<Field, 'name'>> | Field[]
}

const collections:Collections[] = [] // ...

collections.forEach(collection => {
  const fields = Array.isArray(collection.fields)
    ? collection.fields
    : mapRecordToArray(collection.fields, 'name')
})
// Function typings will look like this:
// function mapRecordToArray<Field, Omit<Field, "name">, "name">(record: Record<string, Omit<Field, "name">>, recordKeyName: "name"): Field[]

// Notice the return type: Field[]
Enter fullscreen mode Exit fullscreen mode

Sentry blog image

How to reduce TTFB

In the past few years in the web dev world, we’ve seen a significant push towards rendering our websites on the server. Doing so is better for SEO and performs better on low-powered devices, but one thing we had to sacrifice is TTFB.

In this article, we’ll see how we can identify what makes our TTFB high so we can fix it.

Read more

Top comments (0)

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more