Skip to content
Advertisement

How to declare item types of a zipped list in typescript?

I have two lists like these:

arr1 = [object, object, object...]
arr2 = [10, 2, 5,...]

and combined them using zip:

let zip = arr1.map((x:object, i:number) => [x, arr2[i]]);
// [[object, 10], [object, 2], [object, 5],...]

Then, I want to apply a map on the zip like this, for example:

zip.map((item) => {
  a = item[0] // object
  b = item[1] // number
})

The ‘item’ in the code above implicitly has an ‘any’ type, so I want to define the type like:

item: {object, number}[] // <- imaginary syntax

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][].

const arr1 = [{}, {}, {}];
const arr2 = [10, 2, 5];

let zip: [object, number][] = arr1.map((x, i) => [x, arr2[i]]);

zip.map((item) => {
  const a = item[0] // object
  const b = item[1] // number
});

TypeScipt Playground

Advertisement