13

I know I can do this:

function (value: [boolean, string]) {
   const [boolValue, stringValue] = value;

   // make use of boolValue and stringValue
}

But am I able to do something like this?

// doesn't work
function ([boolValue: boolean, stringValue: string]) {
   // make use of boolValue and stringValue
}
Bergi
  • 630,263
  • 148
  • 957
  • 1,375
Dave Cousineau
  • 12,154
  • 8
  • 64
  • 80
  • What error do you get? It's fine in ES6 (without the types), so this appears to be a TS issue. – Bergi Oct 13 '16 at 19:16
  • @Bergi it gives a lot of errors doing it that way; seems like invalid syntax. First error is `] expected` (instead of `:`) – Dave Cousineau Oct 13 '16 at 19:18
  • 2
    Possible duplicate of [Types in object destructuring](http://stackoverflow.com/questions/39672807/types-in-object-destructuring) –  Oct 13 '16 at 19:27
  • @Bergi Just so you know, I don't think I agree about removing the ES6 tag. This isn't pure ES6, but I'm compiling to ES6. That makes a difference. Maybe it doesn't matter too much in this one case, but just because something is in TypeScript doesn't mean it doesn't have anything to do with ECMAScript. – Dave Cousineau Oct 17 '16 at 15:50
  • 1
    @Sahuagin I'd argue that the question is only about the type error, which is a typescript-only topic. The compilation target hardly makes a difference for that. – Bergi Oct 17 '16 at 16:02

1 Answers1

21

Ok I figured it out, might as well post as an answer. This works:

function ([boolValue, stringValue]: [boolean, string]) {
   // make use of boolValue and stringValue
}
Dave Cousineau
  • 12,154
  • 8
  • 64
  • 80
  • 3
    Covered quite well at https://blog.mariusschulz.com/2015/11/13/typing-destructured-object-parameters-in-typescript. –  Oct 13 '16 at 19:28
  • I had to wrestle with the compiler to get this to work, it was convinced that the argument [true, 'foo'] was (boolean|string)[]. I had to explicitly cast it to [boolean, string]. – Floegipoky Mar 26 '20 at 15:34