Home > Back-end >  TS error when descturturing Block scoped variable cannot be used before its declaration
TS error when descturturing Block scoped variable cannot be used before its declaration

Time:11-24

Hi guys I have the following code written in typescript

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


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

Whe I use the second line I'm getting the error Block scoped variable pageCollection can not be used before its declaration

And when I remove brackets in the second line

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

then I get the following error Cannot find name 'forEach'.

Does anyone know what could be a potential problem?

CodePudding user response:

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


const items = data?.pageCollection?.items ?? []

items.forEach((page) => {
      console.log('PAGEEE', page)
})

Make the code like this. This might work

CodePudding user response:

The problem is a missing ; that isn't optional. You need it at the end of the first statement because otherwise JavaScript (and TypeScript) think the second statement is part of it:

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

If you're going to code relying on automatic semicolon insertion, it's important to be sure you know the rules for where you need an explicit semicolon. In general, if a line starts with a ( or [, you need the ; at the end of the previous line (technically it varies depending on what the previous line is, but it's safer just to always do it).


Side note: There's no need for the spread where you're calling forEach, just:

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

And I'd use for-of instead, but it's a matter of style:

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