アロー関数 (arrow function)
JavaScriptの関数は関数式に加えて、もうひとつの書き方があります。それがアロー関数(arrow function)です。
javascript// 関数式const hello = function (name) {return `Hello, ${name}!`;};// アロー関数const hello = (name) => {return `Hello, ${name}!`;};
javascript// 関数式const hello = function (name) {return `Hello, ${name}!`;};// アロー関数const hello = (name) => {return `Hello, ${name}!`;};
アロー関数は関数式に比べて短く書けるのが特徴的です。引数が1つだけの場合は、引数のカッコが省略できます。
javascriptconst hello = name => {return `Hello, ${name}!`;};
javascriptconst hello = name => {return `Hello, ${name}!`;};
さらに、関数内のコードが式1つだけの場合は、ブレースとreturnが省略できます。
javascriptconst hello = name => `Hello, ${name}!`;
javascriptconst hello = name => `Hello, ${name}!`;
return を省略したアロー関数でオブジェクトリテラルを返したい時はそのまま返すことができません。
typescriptconst func = () => {x: 1}; // この書き方は誤りconsole.log(func());//=> undefined
typescriptconst func = () => {x: 1}; // この書き方は誤りconsole.log(func());//=> undefined
このときはオブジェクトリテラルを() で括ることで返すことができます。
typescriptconst func = () => ({ x: 1 });console.log(func());//=> { x: 1 }
typescriptconst func = () => ({ x: 1 });console.log(func());//=> { x: 1 }
アロー関数の型注釈#
TypeScriptでのアロー関数の型注釈は関数宣言と同様です。
typescriptconst increment = (num: number): number => num + 1;
typescriptconst increment = (num: number): number => num + 1;
アロー関数でカッコを省略した記述をした場合には、引数と戻り値のどちらも型注釈を書けません。
typescriptconst increment = num => num + 1;
typescriptconst increment = num => num + 1;
コンパイラーオプションでnoImplicitAnyを有効にしている場合は、引数の型注釈が必須となるため、カッコを省略したアロー関数の記述自体が出来なくなります。
typescriptconst increment = num => num + 1;// ^^^ Parameter 'num' implicitly has an 'any' type.(7006)
typescriptconst increment = num => num + 1;// ^^^ Parameter 'num' implicitly has an 'any' type.(7006)
noImplicitAnyが有効になっていても、関数引数に直接アロー関数を書く場合は型注釈を省略できます。
typescript[1, 2, 3].map((num) => num + 1);
typescript[1, 2, 3].map((num) => num + 1);