简体   繁体   中英

ES6/TS: Object destructuring in function call

What would be a witty ES6+/TS shorthand to achieve object destructuring in a function call ?

Let's assume a Javascript function that is widely used and cannot have its signature changed

const foo = (b, a) => console.log(b, a);
foo(66,55);                  // 66, 55

And an object that is used to supply values for call parameters

const o = {a: 55, b: 66 };
foo(o.b, o.a);               // 66, 55       <-- can we find a short-hand ?    

Some calls not hitting the target

    foo(...Object.values(o)) // 55, 66 (no, JS object keys are unordered by definition)
    foo(...o);               // TypeError (short, but not valid, illustration only)
    foo(({b, a} = o));       // {a: 55, b: 66} undefined (no error, but we want 66, 55)

If you cannot change the signatur of the function, then you have to call it with each argument in the correct order.

And that is not possible for object deconstruction since a map dont has any order.

You can do something like that with apply :

foo.apply(null, Object.values(o));

But you are not guaranteed the order of the values.

function foo(a,b){return a*b-a}
foo(3,1) // => 0
foo(1,3) // => 2
var o1 = {a:3,b:1}
foo.apply(null,Object.values(o1)) // => 2
var o2 = {b:3, a:1}
foo.apply(null,Object.values(o2)) // => 0

So there are not any witty way to do it.

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