我想将默认值设置为可选参数。原代码中,该函数包含多个参数,调用方式如下,其中options
为可选参数,可以包含多个可选参数:
func(arg1, arg2, options)
为简单起见,我删除了以下示例中的前两个参数。我目前正在这样做:
function test({ a = true, b = false }: { a?: boolean, b?: boolean } = { a: true, b: false }) {
console.log(a, b);
}
// Examples
test(); // true, false (defaults)
test({ a: false }); // false, false
test({ b: true }); // true, true
test({ a: false, b: true }); // false, true
函数头中有很多冗余。 我正在寻找一种方法来简化代码并消除冗余。
答案 0 :(得分:1)
参数初始化器可以是空对象:
function test({ a = true, b = false }: { a?: boolean, b?: boolean } = {}) {
console.log(a, b);
}