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

62
Visualizações
Convert Object.entries reduce to Generics type

I have the following function in TypeScript, what it does is convert an enum to an array.

function toKeyValList(e: any) {
  return Object.entries(e).reduce((acc: any, val: any[]) => {
    acc.push({ key: val[0], value: val[1] });
    return acc;
  }, []);
}

enum IncidentRecordStatus {
  IN_PROCESS = 'IN_PROCESS',
  CLOSE = 'CLOSE',
}

const list = toKeyValList(IncidentRecordStatus);

[LOG]: [{
  "key": "IN_PROCESS",
  "value": "IN_PROCESS"
}, {
  "key": "CLOSE",
  "value": "CLOSE"
}] 


I would like to convert it to a generic function without using the "any" type

I tried this way, but I get an error

export function toKeyValList<T>(e: T): T {
  return (Object.entries(e) as Array<[keyof T, T[keyof T]]>).reduce((acc, [key, value]) => {
    acc.push({ key: key, value: value });
    return acc;
  }, e as T);
}

what would be the correct way to do it?

about 4 years ago · Juan Pablo Isaza
2 Respostas
Responde à pergunta

0

I could not understand where that LOG variable is coming from, but here's the rest of it :

interface keyValuePair {
    key: string,
    value: string,
}

function toKeyValList<T extends object>(e: T) : keyValuePair[] {
  return Object.entries(e).reduce((acc, val : [string, string]) => {
    acc.push({ key: val[0], value: val[1] });
    return acc;
  }, [] as keyValuePair[]);
}

enum IncidentRecordStatus {
  IN_PROCESS = 'IN_PROCESS',
  CLOSE = 'CLOSE',
}

const list = toKeyValList(IncidentRecordStatus);

This would return :

[{
  "key": "IN_PROCESS",
  "value": "IN_PROCESS"
}, {
  "key": "CLOSE",
  "value": "CLOSE"
}] 
about 4 years ago · Juan Pablo Isaza Relatório

0

If you want to infer return type, try to avoid mutations in TypeScript. Consider this example:

const toKeyValList = <
  Obj extends Record<string, string>
>(obj: Obj) =>
  Object
    .entries(obj)
    .reduce<{ key: string, value: string }[]>(
      (acc, [key, value]) => [...acc, { key, value }],
      []
    );

enum IncidentRecordStatus {
  IN_PROCESS = 'IN_PROCESS',
  CLOSE = 'CLOSE',
}

// {
//     key: string;
//     value: string;
// }[]
const list = toKeyValList(IncidentRecordStatus);

Playground

See my article about TS mutations

about 4 years ago · Juan Pablo Isaza Relatório
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