0

Please see this minimum function

function addX({ num = 1 }) {
  return num + 1;
}

The above function has done two things

  1. Deconstruct function parameter
  2. Assign default value

Now, I can use the function like this:

add({ num: 2 }); // valid
add({}); // valid

However, I can't use it like this

add(); // Expected 1 arguments, but got 0

I can't find a way to tell TypeScript the whole object is optional

// Invalid
function add({ num = 1 }?) {
  return num + 1;
}

// Invalid
function add({ num = 1 }?: { num: number }) {
  return num + 1;
}

How can I achieve it?

1 Answer 1

1

How about this

function addX({ num = 1 } = {num: 1}) {
  return num + 1;
}

addX() // returns 2

addX({}) // returns 2

addX({num: 2}) // returns 3
Sign up to request clarification or add additional context in comments.

2 Comments

Neat! I think this is the only way.
Even easier as function addX({ num = 1 } = {}) since you already have a default value for num

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.