0

I have an array of objects I want to destructure, retrieving both the first object and a value within it:

const [{ a }] = ([firstObjectInArray] = [
  {
    a: 1,
  },
  {
    b: 2,
  },
]);
console.log(a); // 1
console.log(firstObjectInArray); // { a: 1 }

In Javascript this works; but in TypeScript this returns

Cannot find name 'firstObjectInArray'.ts(2304)

I'm trying to figure out how to type that in order to avoid the error.

Emille C.
  • 562
  • 1
  • 7
  • 23

1 Answers1

1

As firstObjectInArray isn't part of your declaration (it's just an expression), it's an assignment to an undeclared variable.

To solve the issue, you have two ways:

  • Do it in two steps:

    const [firstObjectInArray] = [
        {
          a: 1,
        },
        {
          b: 2,
        },
      ];
    const {a} = firstObjectInArray
    console.log(a); // 1
    console.log(firstObjectInArray); // { a: 1 }
  • Declare the firstObjectInArray earlier:

    let firstObjectInArray; //<-- This can't be made `const`, as it has no initializer
    const [{ a }] = ([firstObjectInArray] = [
      {
        a: 1,
      },
      {
        b: 2,
      },
    ]);
    console.log(a); // 1
    console.log(firstObjectInArray); // { a: 1 }
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
FZs
  • 16,581
  • 13
  • 41
  • 50