PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, December 13, 2022

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

 December 13, 2022     javascript, loops, syntax, typescript     No comments   

Issue

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.


Solution

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



Answered By - Samathingamajig
Answer Checked By - Katrina (PHPFixing Volunteer)
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

Note: Only a member of this blog may post a comment.

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing