Skip to content
Advertisement

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:

JavaScript

In Javascript this works; but in TypeScript this returns

JavaScript

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

Advertisement

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:

    JavaScript
  • Declare the firstObjectInArray earlier:

    JavaScript
User contributions licensed under: CC BY-SA
1 People found this is helpful
Advertisement