I have two lists like these:
JavaScript
x
3
1
arr1 = [object, object, object ]
2
arr2 = [10, 2, 5, ]
3
and combined them using zip:
JavaScript
1
3
1
let zip = arr1.map((x:object, i:number) => [x, arr2[i]]);
2
// [[object, 10], [object, 2], [object, 5],...]
3
Then, I want to apply a map on the zip like this, for example:
JavaScript
1
5
1
zip.map((item) => {
2
a = item[0] // object
3
b = item[1] // number
4
})
5
The ‘item’ in the code above implicitly has an ‘any’ type, so I want to define the type like:
JavaScript
1
2
1
item: {object, number}[] // <- imaginary syntax
2
but this doesn’t work. Does anyone know how to define the type, for a case like this? I can solve the error, by simply write it as item: any[], but I don’t want to use ‘any’ in my code.
Advertisement
Answer
Your “imaginary syntax” is very close to the real syntax: [object, number]
, and for an array of these arrays, [object, number][]
.
JavaScript
1
10
10
1
const arr1 = [{}, {}, {}];
2
const arr2 = [10, 2, 5];
3
4
let zip: [object, number][] = arr1.map((x, i) => [x, arr2[i]]);
5
6
zip.map((item) => {
7
const a = item[0] // object
8
const b = item[1] // number
9
});
10