Pete V. Pete V. - 2 months ago 16
Javascript Question

Destructuring but also returning the source object

One can do

import Foo, { bar } from 'foo-with-bar'


However, is something like

let { * as Foo, bar } = getFooBar()


possible?

Let's assume
getFooBar()
and the
foo-with-bar
module return

{ foo: 1, bar: a => console.log(a) }


and after the
import
/
let
, this is expected to print
1
:

bar(Foo.foo)

Answer

No, if you're doing destructuring you already have split the object up in properties. However you can just use two assignments:

let Foo = getFooBar();
let { bar } = Foo;

or:

let Foo, { bar } = Foo = getFooBar(); // very questionable and unmaintainable
let Foo = getFooBar(), { var } = Foo; // better

There is also a object rest property proposal with an experimental transpiler plugin that lets you do

let { bar, ...Foo } = getFooBar();

but Foo will be a new object here and lack the bar property.