TypeScript 箭头函数

箭头函数是 ES6 引入的函数简写形式,用 => 定义。在 TypeScript 中它同样可以标注参数与返回类型,写法更简洁;更重要的是箭头函数不绑定自己的 this,能避免回调里 this 丢失的经典问题。

1. 基本语法

把 function 关键字换成"参数 => 表达式或语句块"即可:

const add = (a: number, b: number): number => a + b;
console.log(add(2, 3)); // 输出:5

2. 简化写法

只有一个参数时可省略圆括号;函数体只有一行表达式时自动返回该表达式的值,可省略 return 与花括号:

const double = (x: number) => x * 2; // 单行表达式,自动返回
console.log(double(4));              // 输出:8

const nums: number[] = [1, 2, 3];
console.log(nums.map((n) => n * n)); // 输出:[1, 4, 9]

3. 词法 this

普通函数的 this 由"如何被调用"决定;箭头函数没有自己的 this,会捕获定义处外层作用域的 this,因此回调中 this 依然指向预期对象:

class Counter {
    count = 0;
    start(): void {
        // 箭头函数内的 this 始终指向 Counter 实例
        setInterval(() => {
            this.count++;
            console.log(this.count);
        }, 1000);
    }
}
// 若改成普通 function,这里的 this 会指向全局对象或 undefined

4. 与普通函数的区别

  • 不能用 new 调用:箭头函数不是构造函数,也没有 prototype。
  • 没有自己的 arguments 对象,可用剩余参数 ...args 替代。
  • 不能用作生成器函数(生成器必须用 function* 声明)。
  • 不支持动态 this,适合回调但不适合需要运行时绑定的方法。
// 错误示范:箭头函数不能作为构造函数
// const Box = () => ({ size: 1 });
// new Box(); // 编译报错:不是构造函数

5. 典型使用场景

数组方法、事件监听、Promise 链等回调场景几乎都用箭头函数:

const users: string[] = ["小明", "小红"];
const greetings = users.map((name: string) => `你好,${name}`);
console.log(greetings); // 输出:['你好,小明', '你好,小红']

小结

箭头函数让代码更短,并通过词法 this 解决了回调中的 this 困惑。除了需要动态 this、作为构造函数、生成器等少数场合,日常开发优先使用箭头函数。

笔记加载中…