【问题标题】:How to pass optional parameter that comes after another optional parameter that you don't wish to specify如何传递您不想指定的另一个可选参数之后的可选参数
【发布时间】:2021-10-22 04:12:34
【问题描述】:

我想传递一个参数来覆盖函数声明中稍后出现的默认参数,而不是另一个我想设为默认的默认参数。这可能吗?这是我想做的一个例子:

function f(a:string, b:number=1, c:string='FOO'){
     // do stuff
}

f('val for a', 'val for c') // want b to still be default of 1

【问题讨论】:

    标签: javascript typescript parameters optional-parameters optional-arguments


    【解决方案1】:

    根据文档,您需要将b 显式设置为undefined 以获得默认值。

    function test(a = 1, b = 2, c = 3) {
        console.log(a, b, c);
    }
    
    test(undefined, 42, undefined);

    【讨论】:

    • 听起来无法做到,我必须这样做。谢谢。解决了
    【解决方案2】:

    您可以使用undefined 来获得默认值。这是您可以以良好的风格完成这件事的方法

    function test(a:string, b:number=1, c:string='FOO') {
        //other stuff
    }
    
    let _ = undefined
    
    test('val for a', _, 'val for c');
    

    【讨论】:

      猜你喜欢
      • 2014-12-04
      • 1970-01-01
      • 2020-03-11
      • 1970-01-01
      • 2018-09-10
      • 1970-01-01
      • 2014-12-09
      • 1970-01-01
      • 2010-11-14
      相关资源
      最近更新 更多