Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

132
Views
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 answers
Answer question

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 Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!