2

If I have a tuple how can I set it to a function for the input arguments?

type addArgs = [number, number]

const add = (a, b): number => {
  return a + b;
}

I tried something like this but it does not work:

type addArgs = [number, number]

const add = (...[a, b]: addArgs): number => {
  return a + b;
}

1 Answer 1

3

You just need to use tuples in rest parameters:

type addArgs = [number, number]

const add = (...args: addArgs): number => {
  const [a, b] = args;
  return a + b;
}
add(1, 2);

We can't use de-structing in rest parameters unfortunately so we need to destructure in the function body and we do loose parameter names when calling, but this is the best that can be done

Sign up to request clarification or add additional context in comments.

Comments

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.