Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

273
Visualizações
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!

about 4 years ago · Juan Pablo Isaza
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda