简体   繁体   English

使用 TypeScript 动态返回对象属性类型

[英]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?任何人都可以帮助定义返回类型吗?

.reduce inferred types will be usually be defined as the accumulator's start value. .reduce推断类型通常被定义为累加器的起始值。 I usually end up doing this when I have a function that returns a reduce d value:当我有一个返回reduce d 值的函数时,我通常会这样做:

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>
  );
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM