Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

133
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda