関数宣言 (function declaration)
関数宣言構文#
JavaScriptの関数宣言はfunction構文を使います。
jsfunctionhello () {return "hello";}
jsfunctionhello () {return "hello";}
関数宣言構文の型注釈#
TypeScriptでは関数宣言の引数と戻り値に型注釈を書けます。
tsfunctionincrement (num : number): number {returnnum + 1;}
tsfunctionincrement (num : number): number {returnnum + 1;}
引数の型注釈を省略した場合、コンパイラーはany型と暗黙的に解釈します。
tsfunctionincrement (num ): number {returnnum + 1;}
tsfunctionincrement (num ): number {returnnum + 1;}
コンパイラーオプションのnoImplicitAnyをtrueに設定することで、引数の型注釈を必須にできます。
tsfunctionParameter 'num' implicitly has an 'any' type.7006Parameter 'num' implicitly has an 'any' type.increment (): number { num returnnum + 1;}
tsfunctionParameter 'num' implicitly has an 'any' type.7006Parameter 'num' implicitly has an 'any' type.increment (): number { num returnnum + 1;}
次の例のように定義済みの関数プロパティに再代入する形で関数を上書きする場合はbutton.onclickの引数eventの型がMouseEventと定義されているため、その型情報から代入する関数の引数の型を省略しても、eventの型をMousetEventと推論してくれます。
tsconstbutton =document .createElement ("button");button .onclick = function (event ) {console .log (event .target );Property 'hoge' does not exist on type 'MouseEvent'.2339Property 'hoge' does not exist on type 'MouseEvent'.console .log (event .); hoge };
tsconstbutton =document .createElement ("button");button .onclick = function (event ) {console .log (event .target );Property 'hoge' does not exist on type 'MouseEvent'.2339Property 'hoge' does not exist on type 'MouseEvent'.console .log (event .); hoge };
戻り値の型注釈を省略した場合、コンパイラーがコードから型推論します。
tsfunctionincrement (num : number) {returnnum + 1;}constvalue =increment (1);
tsfunctionincrement (num : number) {returnnum + 1;}constvalue =increment (1);
returnが複数あり違う型を返している場合推論される型はユニオン型になります。
tsfunctiongetFirst (items : number[]) {if (typeofitems [0] === "number") {returnitems [0];}return null;}getFirst ([1, 2, 3]);
tsfunctiongetFirst (items : number[]) {if (typeofitems [0] === "number") {returnitems [0];}return null;}getFirst ([1, 2, 3]);