I have an array of objects I want to destructure, retrieving both the first object and a value within it:
JavaScript
x
12
12
1
const [{ a }] = ([firstObjectInArray] = [
2
{
3
a: 1,
4
},
5
{
6
b: 2,
7
},
8
]);
9
console.log(a); // 1
10
console.log(firstObjectInArray); // { a: 1 }
11
12
In Javascript this works; but in TypeScript this returns
JavaScript
1
2
1
Cannot find name 'firstObjectInArray'.ts(2304)
2
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:
JavaScript111111const [firstObjectInArray] = [
2{
3a: 1,
4},
5{
6b: 2,
7},
8];
9const {a} = firstObjectInArray
10console.log(a); // 1
11console.log(firstObjectInArray); // { a: 1 }
Declare the
firstObjectInArray
earlier:JavaScript111111let firstObjectInArray; //<-- This can't be made `const`, as it has no initializer
2const [{ a }] = ([firstObjectInArray] = [
3{
4a: 1,
5},
6{
7b: 2,
8},
9]);
10console.log(a); // 1
11console.log(firstObjectInArray); // { a: 1 }