我想要一个带有可选参数和带有默认值的参数的函数,如下所示,但是如何调用该函数呢?
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
答案 0 :(得分:1)
后两个调用假定您有一个options参数。即一个收集各种选项的对象,但是您的函数定义为仅接受参数列表。如果要保持通话格式,则需要更改定义,类似以下内容:
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)
}