Skip to content

TypeScript destructure array of objects, both first object and a value within it

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.

Answer

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 }