Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Types when destructuring arrays

function f([a,b,c]) {   // this works but a,b and c are any } 

it's possible write something like that?

function f([a: number,b: number,c: number]) {   // being a, b and c typed as number  } 
like image 352
thr0w Avatar asked Aug 10 '15 15:08

thr0w


People also ask

Can we Destructure array?

To destructure an array in JavaScript, we use the square brackets [] to store the variable name which will be assigned to the name of the array storing the element.

How do you Destructure an array within an array?

Similarly, to destructure arrays to multiple variables, use the square brackets [ ] instead of curly brackets. Arrays: const [variable1,variable2] = arrayName; Note: In the case of destructuring objects, the name of the variables should be the same as the name of the properties of the object.

How does Destructuring an array work?

Destructuring in JavaScript is a simplified method of extracting multiple properties from an array by taking the structure and deconstructing it down into its own constituent parts through assignments by using a syntax that looks similar to array literals.

Can you give an example of Destructuring an object or an array?

In the first line, we are declaring a new variable studentsArr , and assigning it the value of an array of student names. Line 2 is where we destructure. In line 2 we declare three variables; first , second , and third . By declaring them on the left-hand side, we initiate destructuring.


2 Answers

This is the proper syntax for destructuring an array inside an argument list:

function f([a,b,c]: [number, number, number]) {  } 
like image 141
Ryan Cavanaugh Avatar answered Oct 14 '22 04:10

Ryan Cavanaugh


Yes, it is. In TypeScript, you do it with types of array in a simple way, creating tuples.

type StringKeyValuePair = [string, string]; 

You can do what you want by naming the array:

function f(xs: [number, number, number]) {} 

But you wouldn't name the interal parameter. Another possibility is use destructuring by pairs:

function f([a,b,c]: [number, number, number]) {} 
like image 35
Marcelo Camargo Avatar answered Oct 14 '22 04:10

Marcelo Camargo