Home > Software design >  Dynamic return type of object properties using TypeScript
Dynamic return type of object properties using TypeScript

Time:10-28

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?

CodePudding user response:

.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>
  );
}
  • Related