LoginSignup
2
2

More than 1 year has passed since last update.

【TypeScript入門】可変長引数、レストパラメーターとは

Posted at

まとめ

可変長引数は内部的にanyとして扱われるので、安全ではない。そこでTypeScriptでは、レストパラメーターを使用する。

可変長引数とは

  • 関数の呼び出しの際に引数の数をいくつ渡してもOK
  • 全く型安全ではない
  • argumentsで受け取るやつ

レストパラメーター

  • パラメーターに...を用いることで型定義できる。
  • パラメーターの最後に1つだけ指定できる
const sumProductsPrice = (...productsPrice: number[]): number => {
  return productsPrice.reduce((prevTotal, productPrice) => {
    return prevTotal + productPrice
  }, 0) // 0: prevTotalの初期値
}

 const sum = sumProductsPrice(1, 2, 3,)
 console.log('sample: Total:', sum)
//sample: Total: 6

2
2
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
2
2