0

Say I have an object like this (from the external library which I can't change):

const anotherObj = {
  func1: (id: number, name: string) => {},
  func2: (helper: () => void) => {},
};

export const obj = {
   func1: (...args: Parameters<typeof anotherObj.func1>) => anotherObj.func1(...args),
   func2: (...args: Parameters<typeof anotherObj.func2>) => anotherObj.func2(...args),
}

Now I want to write a helper function to call a function inside the obj but it throws an error while passing the args

const helper = <K extends keyof typeof obj>(key: K, ...args: Parameters<typeof obj[K]>) => {
  return obj[key](...args);
  //                 ^ Error: Argument of type 'string | number | (() => void)' is not assignable to parameter of type 'number & (() => void)'.
};

What could I do wrong here? Sorry for my bad English!

hungps
  • 389
  • 2
  • 11
  • This pattern is unsafe and TS does not support it without type assertion. See [this](https://stackoverflow.com/questions/73892029/typescript-doesnt-infer-correct-type-with-conditionals/73892671#73892671) answer, [this](https://stackoverflow.com/questions/68966710/how-to-get-concrete-type-from-mapping-variable/68967097#68967097) and [my article](https://catchts.com/react-props) – captain-yossarian from Ukraine Sep 30 '22 at 13:20

0 Answers0