関数: ロジックのまとまり
宣言、アロー関数、高階関数。thisの違いに注意。
アロー関数
=>で定義する短い構文。thisを引き継ぐ。
高階関数
関数を受け取るか返す関数。
Rest
残りの引数をまとめる構文。
関数基礎
// 関数宣言function greet(name: string): string { return `Hello, ${name}!`;}
// アロー関数const add = (a: number, b: number): number => a + b;
// デフォルト引数function greet(name = 'World') { return `Hello, ${name}!`;}Bad
// ❌ Bad: this が失われるclass Counter { count = 0; increment() { setTimeout(function() { this.count++; // this は undefined }, 1000); }}Good
// ✅ Good: アロー関数で this を維持class Counter { count = 0; increment() { setTimeout(() => { this.count++; // this はCounter }, 1000); }}高度なパターン
// Rest パラメータfunction sum(...nums: number[]) { return nums.reduce((a, b) => a + b, 0);}
// 高階関数const withLogging = (fn: Function) => (...args: any[]) => { console.log('Called with:', args); return fn(...args);};
// 即時実行関数式 (IIFE)const result = (() => { const secret = 'hidden'; return secret.length;})();合格ライン
アロー関数の this の挙動を説明できる
Rest パラメータを使える
演習課題
課題1: 関数宣言
関数宣言とアロー関数を使い分けてください。
課題2: Rest パラメータ
Rest パラメータで可変長引数を処理してください。