tsiege
tsiege

Reputation: 507

How to define function in TypeScript with a destrcutured array as parameter

I'm new to TS, but am very experienced in the latest on JavaScript. I'd like to use features that I'm familiar with in ES6. One in particular is using array destructuring in a function's parameters. I've learned that you can use an interface in TS to do object destructuring like so:

interface FooParameters {
  bar: any
}

function foo ({ bar }: FooParameters) {
  console.log(bar)
}

foo({ bar: 'fizz' })
// logs "fizz"

But I can't seem to find documentation on converting the following JS to TS

function foo ([bar]) {
  console.log(bar)
}

foo(['fizz'])
// logs "fizz"

Upvotes: 1

Views: 45

Answers (2)

tsiege
tsiege

Reputation: 507

After playing around with advice from @bnieland I was able to surmise the right answer. I needed to define an inline tuple with the corresponding parameters and their types.

function foo ([bar]: [string]) {
  console.log(bar)
}

foo(['fizz']) // logs "fizz"

Upvotes: 1

bnieland
bnieland

Reputation: 6496

function foo(...barArray: FooParameters[]) {}

Upvotes: 2

Related Questions