简体   繁体   English

如何在 typescript 中混合使用可选参数和参数与默认值

[英]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,它采用可选参数和默认值参数,如下所示,但是如何调用 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.后两个调用假定您有一个 options 参数。 Ie an object collecting various options but your function is defined to only accept a list of arguments.即一个 object 收集各种选项,但您的 function 被定义为只接受 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)
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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