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

141
Visualizações
Dynamic return type of object properties using TypeScript

I have a function that receive an object and return an object of methods with the same property names:

function someGenerator<P extends {}>(params: P) {
  return Object.keys(params).reduce((acc, key) => ({
    ...acc,
    [key]: () => {
      console.log(params[key]);
    },
  }), {});
}

Basically I want to use it like so:

type Params = {
  str: string;
}

const params = {
  str: 'some text',
}

const someInstance = someGenerator<Params>(params);

someInstance.str();

I tried to define the return type of that function:

type ReturnType<P> = {
  [K in keyof P]: () => void;
}

But this type doesn't work as I expected, because the definition of the return type does not hold the params like it should.

Can anyone help with define the return type?

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

0

.reduce inferred types will be usually be defined as the accumulator's start value. I usually end up doing this when I have a function that returns a reduced value:

function someGenerator<P extends Record<string, any>>(params: P) {
  return Object.keys(params).reduce(
    (acc, key) => ({
      ...acc,
      [key]: () => {
        console.log(params[key]);
      }
    }),
    {} as Record<keyof P, () => void>
  );
}
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