21

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?

11
  • Of course it is possible, why would it not? Haven't you tried it? It works since ES6. Commented Jun 22, 2017 at 0:44
  • yeah I tried it :( with TypeScript, that is Commented Jun 22, 2017 at 0:45
  • what is this called, so I google how to do it with TypeScript Commented Jun 22, 2017 at 0:45
  • Maybe you should make it a TypeScript question then and post the error message you got from the compiler. I guess the type checker doesn't like it, similar to the problem with spread arguments? Commented Jun 22, 2017 at 0:46
  • 1
    Sure, thanks for the edit! Commented Jun 22, 2017 at 0:49

1 Answer 1

33

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 () { }
]);
Sign up to request clarification or add additional context in comments.

1 Comment

What about an arbitrary length array? or destructuring the first few elements and collecting the remainder with the spread operator?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.