简体   繁体   中英

How can I make TypeScript deconstruct function parameter, assign default value, and optional whole object type at same time?

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?

How about this

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

addX() // returns 2

addX({}) // returns 2

addX({num: 2}) // returns 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM