簡體   English   中英

如何在 typescript 中混合使用可選參數和參數與默認值

[英]how to mix use of optional parameter and parameter with default value in typescript

我想要一個 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

后兩個調用假定您有一個 options 參數。 即一個 object 收集各種選項,但您的 function 被定義為只接受 arguments 的列表。 如果要保持調用格式,則需要更改定義,類似於以下內容:

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