1

I have an array of object instances with different types.

var instances: any = [];
instances["Object1"] = new TypeA();
instances["ObjectB"] = new TypeB();

Each type have own methods with different names and number of arguments. I want to call this methods by calling one function and passing to it data to identify the method to call and necessary argument values(I send this data from client).

function CallMethod(data){
  let args = data.args;// it's array
  instances[data.objectId][data.methodId](??????); 
}

Is it possible to automatic decompose args array to pass his values as different function arguments?

Like this:

instances[data.objectId][data.methodId](args[0], args[1], ... args[n]); 
hdnn
  • 1,807
  • 3
  • 13
  • 20
  • Either use the spread operator, either use `.call` or `.apply` https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/call , https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Function/apply – briosheje Apr 10 '19 at 14:20
  • I wanted to provide a type safe version of this ... but I guess since it got quickly closed I can't anymore :( – Titian Cernicova-Dragomir Apr 10 '19 at 14:37
  • 1
    `class TypeA { method(s: string) { } } class TypeB { foo(s: string, n: number) { } bar(n: number) { } } var instances = { "Object1": new TypeA(), "ObjectB": new TypeB(), } function CallMethod< K extends keyof typeof instances, M extends keyof typeof instances[K]>(data: { objectId: K } & { methodId: M } & { args: typeof instances[K][M] extends (...a: any) => any ? Parameters : never }) { let args = data.args; (instances[data.objectId][data.methodId] as any)(...args); }` – Titian Cernicova-Dragomir Apr 10 '19 at 14:38
  • Sounds great, but can you explain your solution? Especially this line: ```{ args: typeof instances[K][M] extends (...a: any) => any ? Parameters : never }``` – hdnn Apr 11 '19 at 05:46

3 Answers3

0

Use the Spread Syntax

function CallMethod(data){
  let args = data.args;// it's array
  instances[data.objectId][data.methodId](...args); 
}
Maheer Ali
  • 35,834
  • 5
  • 42
  • 73
0

You can destruct the array for function parameters using ... It is also known as spread. You can read more about it here.

instances[data.objectId][data.methodId](...args); 

so your function will be:

function CallMethod(data){
    let args = data.args;// it's array
    instances[data.objectId][data.methodId](...args); 
}
Ashish
  • 4,206
  • 16
  • 45
0

spread operator will work here

function CallMethod(data){
  let args = data.args;
  instances[data.objectId][data.methodId](...args); 
}
Joseph
  • 682
  • 5
  • 17