LoginSignup
0
0

typescriptの可変長引数は0個を許容している

Last updated at Posted at 2023-11-16

typescriptにおける可変長引数

  • 可変長引数とは、長さの決まっていない関数の引数のことで、typescriptでは残余引数(rest parameter)とも呼ばれる
  • 0個を許容している

例) 関数exampleの引数hogeは、可変長引数

function example (...hoges[]: Hoge) {
    for( const hoge of hoges ) {
        // 処理を書く
    }
    return result;
}

例2) hogeが0個だと都合が悪いときは、firstHogeを引数に用意する

function example (firstHoge: Hoge, ...hoges[]: Hoge) {
    let result = firstHoge;
    for( const hoge of hoges ) {
        result = result + hoge;
    }
    return result;
}

参考記事

この記事は

実務で教えていただいたことに加えて、記事を読んで勉強したことの覚書です。
あくまでtypescriptの挙動を記載しているだけであり、typescript以外の言語での可変長引数の扱いについては勉強不足のため比較できていません。

0
0
1

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
0
0