简体   繁体   中英

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

I am trying to migrate the following covert javascript function to typescript, but with no luck, anyone can help, thanks.

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'}

I tried the following, but not working:

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

Here is a start for you. It is also in the playground here .

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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