0

I kind of like the array destructuring in ES6.

I have a test case where I query the buttons and want to directly pull out the button variables rather than mess around with arrays, like so:

let [backButton, forwardButton]: HTMLElement[] = await screen.findAllByRole('button')
fireEvent.click(forwardButton);

However I want to repeat the destructuring later in the code, like so:

let [backButton, forwardButton]: HTMLElement[] = await screen.findAllByRole('button')
fireEvent.click(forwardButton);

//do some stuff

[backButton, forwardButton]: HTMLElement[] = await screen.findAllByRole('button')
fireEvent.click(backButton);

Unfortunately Typescript does not seem to allow me to do this.

I get an error

TS7053: Element implicitly has an 'any' type because expression of type 'any' can't be used to index type '{ new (): HTMLElement; prototype: HTMLElement; }'.

Is there any way of being able to destructure twice in one block?

5
  • I'm not sure if this is the sole problem (since i don't see how it connects to the error message), but the second destructuring should not have a type. Ie, it should be [backButton, forwardButton] = await screen.findAllByRole('button') Commented Oct 28, 2022 at 11:57
  • perfect! That answers my question .............! Commented Oct 28, 2022 at 12:04
  • please post this as an "answer" Commented Oct 28, 2022 at 12:04
  • You can always post an answer yourself since you were able to resolve the problem. You could also delete the question but since it's not quite a simple "typo", it might be worth keeping for future readers. Commented Oct 28, 2022 at 12:26
  • yeah i know.... but i wanted to reward the guy the points Commented Oct 28, 2022 at 13:14

1 Answer 1

1

The HTMLElement[] type definition is only needed when the variables are first created. When you try to do it again on the second line, you are confusing typescript. So the fix is to remove the type from the second destructuring:

[backButton, forwardButton] = await screen.findAllByRole('button')
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.