#Is it possible to destructure an object and assign its properties to variables in an outer scope?

1 messages · Page 1 of 1 (latest)

green yarrow
#

I have this code:

  let sugarcubeParser: SugarcubeParser;
  let t: TestController;

  beforeAll(async () => {
    const testFramework = await init();
    sugarcubeParser = testFramework.sugarcubeParser;
    t = testFramework.testController;
  });

Is it possible to turn those 3 lines in beforeAll into a single line?

This is init's signature:

export const init = async (): Promise<{
  sugarcubeParser: SugarcubeParser;
  testController: TestController;
}>
junior kernel
#
;({ sugarcubeParser, t } = await init())
green yarrow
junior kernel
green yarrow
junior kernel
#

Yeah.

green yarrow
#

Why did you put a semicolon in front?

junior kernel
#

It's not necessary here, and typically formatters like Prettier will do it for you.

#

It's to prevent code like:

const foo = bar
(baz)

To be interpreted incorrectly as:

const foo = bar(baz)
#

You can see the same being done for:

const foo = bar
;[baz].forEach(...)
green yarrow
#

ah:

If your coding style does not include trailing semicolons, the ( ... ) expression needs to be preceded by a semicolon, or it may be used to execute a function on the previous line.

#

Thanks for the help. I must've glossed over this syntax in the past

junior kernel
#

Yeah it's the same as regular destructuring just without the const/let declaration.

#

The extra ;() is just to fix the syntax ambiguity.

green yarrow
#

To be honest, even if I saw that example, I would've assumed that it needed to be assigning to something within the same block

#

So thanks again @junior kernel