Error in TypeScript occurs when trying to destructure a block-scoped variable before it has been declared

Hello everyone, I have the below code written in TypeScript

  const {
      data: { pageCollection }
    } = await apolloClient.query<PageSlugsQuery>({ query: GET_PAGE_SLUGS })


    ( [...(pageCollection?.items ?? [])].forEach((page) => {
      console.log('PAGEEE', page)
    }))

When I try to use the second line it shows an error message saying

Block scoped variable pageCollection can not be used before its declaration 

However, if I remove the brackets from the second line like this:

  [...(pageCollection?.items ?? [])].forEach((page) => {
      console.log('PAGEEE', page)
    })

I then receive a different error message saying Cannot find name 'forEach'.

Does anyone have any idea what could potentially be causing this issue?

Answer №1

The issue at hand is a crucial missing ; that cannot be overlooked. Without it, JavaScript (as well as TypeScript) interprets the second statement as an extension of the first:

const {
    data: { pageCollection },
} = await apolloClient.query<PageSlugsQuery>({ query: GET_PAGE_SLUGS }); // <===
[...(pageCollection?.items ?? [])].forEach((page) => {
    console.log("PAGEEE", page);
});

If you plan to rely on automatic semicolon insertion when coding, ensure you are familiar with the rules regarding when you absolutely require a explicit semicolon. Typically, if a line starts with a ( or [, you must have the ; at the end of the preceding line (although technically it can vary based on the content of the previous line, it's safer to always include it).


Sidenote: The spread operator within the forEach loop isn't necessary; simply do this instead:

(pageCollection?.items ?? []).forEach((page) => {
    console.log("PAGEEE", page);
});

Personally, I prefer using for-of instead, but this choice may come down to personal style preferences:

for (const page of pageCollection?.items ?? []) {
    console.log("PAGEEE", page);
}

Answer №2

const {
      result
    } = await apolloClient.query<PageSlugsQuery>({ query: GET_PAGE_SLUGS })


const pageItems = result?.pageCollection?.items ?? []

pageItems.forEach((selectedPage) => {
      console.log('PAGE DETAIL', selectedPage)
})

You can try this updated version of the code, it should be functional.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

error : failed to establish a connection to the MongoDB database

Ensure that the first parameter passed to mongoose.connect() or mongoose.createConnection() is a string. MongooseError: The uri parameter for openUri() must be a string, but it was "undefined". Double check that the initial parameter for mongoose.connect() ...

Converting a CSV string into an array only when there is a line break in the body

Need help to convert a CSV string into an array of array of objects. Struggling with handling \n in the incoming request, causing issues with splitting and code errors. The string format includes messages enclosed in ". "id,urn,title,body,ri ...

javascript href clears Internet Explorer webpage

I noticed a strange issue with my HTML page. In Internet Explorer, when I click on the link, it displays the return value on a blank page. However, in Chrome, it simply executes the function without affecting the page appearance. Is there a way to make I ...

Ways to access customer subscriptions in Stripe

I have a customer on Stripe who wants to cancel his subscription. I have checked the documentation for the customer object (here) and the subscription object (here), but I am unsure how to retrieve the subscription id associated with the customer. In order ...

Issue with detecting undefined in a nested function using Typescript

Examining the code snippet provided below, focus on the test getter. Why is it that const name = this.person.name does not result in an error, while const processPerson = () => this.person.name does generate an error? interface Person { name: string; ...

iterate over the array and retrieve all corresponding values using mongodb

I am looking to iterate through an array of objects stored in my MongoDB database and retrieve all indexes that meet a certain condition... For example, here is the array: orders: [ { foodId: { type: mongoose.Types.ObjectId, ...

Is Passport.js' serializeUser and deserializeUser functions never triggering?

Encountering an issue with Passport-local. It seems that neither serializeuser nor deserializeUser are being invoked. Upon researching similar problems on SO, it appears that many others facing this problem were not properly including bodyParser. Below is ...

obtain every potential substring in sequence

After exploring various methods to find possible substrings, I attempted an approach in PHP which can be found here. However, I have specific requirements for generating substrings. For example, if the input string is 'ABCDE', the desired combin ...

Understanding the reverse order of numbers displayed with while loop and innerHTML

function doItAgain() { var loopCount = 5; while(loopCount > 0) { var target = document.getElementById("target"); target.innerHTML = "LoopCount: " + loopCount + "& ...

Having trouble uploading APK to Google Play Developer using Publisher API

Currently, I am in the process of developing a script using nodejs to upload my APK file to Google Play Developer through the Publishing API. However, I have encountered some issues with the upload process. Despite having a valid APK file, the upload is fa ...

Typedoc: only export contents from a particular file are documented

Currently, I am working on developing two npm packages: https://github.com/euberdeveloper/mongo-scanner https://github.com/euberdeveloper/mongo-cleaner My goal is to create documentation for these packages using Typedoc. The main file is index.js p ...

Converting a typename to a type in TypeScript

Is there a way to cast a string with a typename to a type without an explicit mapping in order to use it for an angular component factory? When there is a mapping, the process is straightforward: public readonly typeMap: Map<string, Type<{}>> ...

Unable to convert imported JSON file into an array

Looking to create an array from a file, the following code snippet serves the purpose: 'use strict'; const fs = require('fs'); let results = []; fs.readFile('myfile.json', (err, data) => { if (err) throw err; res ...

Steps for connecting a front-end button to a Node.js event

Recently, I managed to set up a node server that facilitates signing in with Steam and redirecting back to the website. My current query revolves around integrating the sign-in/sign-out buttons into an AngularJS front end and leveraging the server as a pro ...

Include an additional section in the stunning Radar Chart

I am trying to use the amCharts 4 library to create a Radar graph similar to this example: https://i.sstatic.net/9S0ka.png In the example, there are two categories being compared with bullets surrounding each one, right? The code I currently have is as ...

What is the best way to merge two similar arrays of objects into one array object?

Apologies in advance if this question has been asked previously, I'm struggling with how to phrase it. Essentially, the API I'm using is returning an array of similar objects: const response.survey = [ { 1: { id: 1, user: user_1, points: 5 ...

Switch to light mode upon clicking the toggle?

On the top left corner of this page, there's a toggle for "Light/Dark mode". Clicking on 'Light mode' smoothly transitions to dark mode without any issues. However, once it's in Dark mode and you try to switch back to 'light mode&a ...

I am unable to correctly fetch the data string using Jquery Ajax from the server

I have implemented a jQuery Ajax function to check the availability of a username in real-time from the database. If the username is not available, the response is marked as "Unavailable" and vice versa. While I am successfully receiving this response, I a ...

Tips for choosing a particular value in an HTML <script> query

Can someone please help me figure out how to select specific values in a form using a query? I'm trying to extract certain values like Hello and Lorem ipsum..., as well as Hi and Nullam fringilla... from the Content.join(''); section. I apo ...

Assign a default value to empty elements in an array

Here is an example of fetching data in an array: [ { "Id": 111, "Name": "Test 1", "Email": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" data-cfemail="8de8e0ece4e1bccde9e2e0ece4e3a3e3e8f9">[email protect ...