iOSエンジニアのつぶやき

毎朝8:30に iOS 関連の技術について1つぶやいています。まれに釣りについてつぶやく可能性があります。

【TypeScript】A required parameter cannot follow an optional parameter. の対処法

TypeScriptで下記のようなコードを書いていたら A required parameter cannot follow an optional parameter.というErrorに遭遇して、若干ハマったのでメモします。

function hoge(a?: string, b: string) {
  console.log(a)
  console.log(b)
}

結論

結論、エラーメッセージの通りで、TypeScriptでは省略可能な引数の後に、省略不可能な引数を記述することはできません。ですので、今回のような場合は、省略不可能な引数を最初に記述する必要があります。

function hoge(b: string, a?: string) {
  console.log(a)
  console.log(b)
}

てな感じで本日も以上となります🍺

参考

その他の記事

yamato8010.hatenablog.com

yamato8010.hatenablog.com

yamato8010.hatenablog.com