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]); 
4
  • Either use the spread operator, either use .call or .apply developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… , developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/… Commented Apr 10, 2019 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 :( Commented Apr 10, 2019 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<typeof instances[K][M]> : never }) { let args = data.args; (instances[data.objectId][data.methodId] as any)(...args); } Commented Apr 10, 2019 at 14:38
  • Sounds great, but can you explain your solution? Especially this line: { args: typeof instances[K][M] extends (...a: any) => any ? Parameters<typeof instances[K][M]> : never } Commented Apr 11, 2019 at 5:46

3 Answers 3

0

Use the Spread Syntax

function CallMethod(data){
  let args = data.args;// it's array
  instances[data.objectId][data.methodId](...args); 
}
Sign up to request clarification or add additional context in comments.

Comments

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

Comments

0

spread operator will work here

function CallMethod(data){
  let args = data.args;
  instances[data.objectId][data.methodId](...args); 
}

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.