Company logo
  • Empleos
  • Bootcamp
  • Acerca de nosotros
  • Para profesionales
    • Inicio
    • Empleos
    • Cursos y retos
    • Preguntas
    • Profesores
    • Bootcamp
  • Para empresas
    • Inicio
    • Nuestro proceso
    • Planes
    • Pruebas
    • Nómina
    • Blog
    • Comercial
    • Calculadora

0

66
Vistas
Reducing const asserted array of objects to create const asserted normalized map with reduce in Typescript

I'm trying to create a map normalized by object's key from an array of objects using reduce. The array is defined using a const assertion - as const:

const flavors = [
  { type: 'sweet' },
  { type: 'sour' },
] as const;

The desired normalized map looks like this:

const expectedFlavorsMap = {
  'sweet': { type: 'sweet' },
  'sour': { type: 'sour' }
} as const;

Now to create such map, I am using a reduce function so that keys are type and values are the objects itself from the flavors array.

const flavorsMap = flavors.reduce((acc, flavor) => {
  acc[flavor.type] = flavor;
  return acc;
}, {} as any); // any for now

Is it possible to obtain a const asserted object (map) of flavors after using reduce? Here's what I tried, but I can see there is a problem with FlavorsMapType type.

const flavors = [
  { type: 'sweet' },
  { type: 'sour' },
] as const;

type FlavorsType = typeof flavors;

type FlavorsMapType = Record<FlavorsType[number]['type'], FlavorsType[number]>

const flavorsMap = flavors.reduce((acc, flavor) => {
  acc[flavor.type] = flavor;
  return acc;
}, {} as FlavorsMapType);

const expectedFlavorsMap = {
  'sweet': { type: 'sweet' },
  'sour': { type: 'sour' }
} as const;

const sweet = flavorsMap['sweet'];

// err, expected type to be the object {type: 'sweet'}
const sweet2: { readonly type: 'sweet' } = flavorsMap['sweet'];

Typescript playground

Thanks in advance!

7 months ago · Juan Pablo Isaza
Responde la pregunta
Encuentra empleos remotos