Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array destructuring in parameters list, with TypeScript

Tags:

typescript

Using TypeScript, I am trying to figure out how to do array destructuring in the arguments list.

We can use object destructuring like so:

let foo = function({firstname, lastname}){...}

foo({
  firstname: 'ralph',
  lastname: 'lauren'
});

I am wondering if we can do the same thing with array destructuring, it would be very useful for me, something like:

let bar = function([desc, opts, fn]){...}

bar([
  'yes',
   {},
   function(){}
]);

is it possible to do this with an array with TypeScript?

like image 884
Alexander Mills Avatar asked Jun 22 '17 00:06

Alexander Mills


People also ask

How do you Destructure parameters?

Destructuring in JavaScript is used to unpack or segregate values from arrays or properties from object literals into distinct variables, thus it allows us to access only the values required.

What is array Destructuring in typescript?

Destructuring is a JavaScript expression that makes it possible to unpack values from arrays, or properties from objects, into distinct variables. That is, we can extract data from arrays and objects and assign them to variables.

How do you Destructure an object in typescript?

And this is destructuring an object. Let's take the following example: const user = { firstname: 'Chris', lastname: 'Bongers', age: 32 }; const { firstname, age } = user; By using this destructuring, we extract specific properties from an object.

Can we Destructure array?

Destructuring in Arrays. 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. const [var1, var2, ...]


1 Answers

An array of fixed length and types is also called a tuple in TS. We can destructure a tuple argument like:

let bar = function ([desc, opts, fn]: [string, {}, Function]) {


}

bar([
    'yes',
    {},
    function () { }
]);
like image 128
Jokester Avatar answered Nov 20 '22 04:11

Jokester