可选参数的可选默认值
Optional defaults for optional argument
我想为可选参数设置默认值。原代码中,函数包含多个参数,这样调用,其中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
函数头中有很多冗余。 我正在寻找一种方法来简化代码并删除冗余。
参数初始化器可以是空对象:
function test({ a = true, b = false }: { a?: boolean, b?: boolean } = {}) {
console.log(a, b);
}
我想为可选参数设置默认值。原代码中,函数包含多个参数,这样调用,其中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
函数头中有很多冗余。 我正在寻找一种方法来简化代码并删除冗余。
参数初始化器可以是空对象:
function test({ a = true, b = false }: { a?: boolean, b?: boolean } = {}) {
console.log(a, b);
}