简体   繁体   中英

how to mix use of optional parameter and parameter with default value in typescript

I would like to have a function that take optional parameter and parameter with default value something like following, but how can I call the function?


function func(a = '', b?: string, d = false) {
  if (b) {
    console.log(b)
  }
  console.log(a)
  console.log(d)
}
//how to call?
func() //a, false
func({ 'c': '2' }) //2, a, false
func({'a': 'string', 'c': '2', 'd': true}) // 2, string, true

The second two calls assume that you have an options argument. Ie an object collecting various options but your function is defined to only accept a list of arguments. If you want to maintain the call format you would need to change the definition, something along the lines of this:

function func(options?: { a?: string, b?: string, c?: string, d?: boolean })
{
  // Combines default values with inputs
  const { a, b, c, d } = { a: '', d: false, ...options }

  if (b) {
    console.log(b)
  }
  console.log(a)
  console.log(d)
}

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