TypeScript: call a member of an object with arguments

  • A+
Category:Languages
function whatever(object, methodName, args) {   return object[methodName](...args); } 

Can the above be typed so the the following is enforced:

  • methodName is a key of object.
  • object[methodName] is callable and its args are ...args.
  • The return type of whatever(object, methodName, args) is the return type of object[methodName](...args).

The closest thing I could find is the definition of function.apply, but it isn't quite the same as the above.

 


I think this does the trick:

function callMethodWithArgs<   M extends string,   T extends { [m in M]: (...args: Array<any>) => any },   F extends T[M] >(obj: T, methodName: M, args: Parameters<F>) {   return obj[methodName](...args) as ReturnType<F>; } 

Requires TS 3 though!

Comment

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen: