繁体   English   中英

如何迁移到带有对象参数的函数的打字稿,函数属性返回不同

[英]How to migrate to typescript for function taking object parameters with function properties returning differently

我正在尝试将以下covert javascript 函数迁移到打字稿,但没有运气,任何人都可以提供帮助,谢谢。

const convert = (state, obj) => {
  return Object.keys(obj).reduce(
    (aggr, key) => ({ ...aggr, [key]: () => obj[key](state) }), 
    {}
  )
 }

convert(
  { name: 'ron', id: 123 }, 
  { 
    getName: state => state.name,
    getId: state => state.id
  }
) // newObj: {getName: () => 'ron'}

我尝试了以下,但没有工作:

function convert<State, TObj> : {
  [key in keyof TObj]: ()=>ReturnType<TObj[key]>
}

这是你的开始。 它也是在这里的操场上

/**
 * Since `obj` extends `Record<string, Function>`, we know that the `key`
 * values will be of type `string` and that the values themselves will be
 * functions that accept the state and return something unknown.
 */
const convert2 = <
  TState,
  TObj extends Record<string, (state: TState) => unknown>
>(
  state: TState,
  obj: TObj
) => {
  return Object.keys(obj).reduce(
    (aggr, key) => ({ ...aggr, [key]: () => obj[key](state) }),
    {}
  );
};

convert2(
  { name: "ron", id: 123 },
  {
    getName: state => state.name,
    getId: state => state.id,
    /**
     * The implementation of `getFoo` is an error, which is what we want,
     * because `foo` does not exist in the state.
     */
    getFoo: state => state.foo
  }
);

暂无
暂无

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

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