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[]
}
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[] = [] // ...
function getFields(){
return collections.map(collection => {
const fields = Array.isArray(collection.fields)
? collection.fields
: mapRecordToArray(collection.fields, 'name')
})
}
// Function return type will be Field[]