1

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"

2 Answers 2

2
function foo(...barArray: FooParameters[]) {}
Sign up to request clarification or add additional context in comments.

6 Comments

It's unclear to me how a spread operator here would give me access to the parameter bar. Wouldn't this allow several variables to put into an array? I want to take a variable out of one.
In this case, ... is concidered to be a "rest" operator (blog.mariusschulz.com/2016/12/23/…).
Thanks for the clarification. I got it to work but I had to do the following to get it to work. You might want to edit your answer to clarify function bar([bar]: FooParameters[]) { console.log(bar) }
interesting; so you do not need FooParameters, correct? Otherwise you will need to use: let a = ['fizz'].map<FooParameters>((v) => ({ bar: v })); foo(...a);
It seems like the correct answer is function foo([bar]: [string)) {}
|
1

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"

6 Comments

I have never seen that construct for an array (i.e. function foo ([bar]: [string])). Is it any different than function foo ([bar]: [string])?
fyi: I am sure you are aware, but TypeScript Playground is an excellent place to try out these pure language questions!
Thanks for the tip! But could you clarify your first response? Those two declarations look the same to me
Oops! You are correct! Here is what I meant! function foo ([bar]: [string]) vs. function foo ([bar]: string[])
Sorry, I've been digging a bit deeper, and I realized that function foo ([bar]: string[]) does work for the above code. I also, realized this example I gave didn't address my problem because I was trying to destructure two parameters from the array and they were different types, which is why I needed the tuple
|

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.