在 TypeScript(也包括 JavaScript)中,=>
是 箭头函数(Arrow Function) 的语法,用来定义一个匿名函数,也叫“箭头函数表达式”。
一、基本语法
const fn = (参数) => {
// 函数体
};
比如:
const add = (a: number, b: number): number => {
return a + b;
};
等价于传统写法:
function add(a: number, b: number): number {
return a + b;
}
二、简写规则
如果函数体只有一行并且是返回值,可以省略 {}
和 return
:
const square = (x: number) => x * x;
相当于:
const square = (x: number) => {
return x * x;
};
三、没有参数时
需要加空括号:
const sayHi = () => console.log('Hi');
四、只有一个参数时
可以省略括号(但建议加上):
const double = x => x * 2; // 可以,但不推荐
五、箭头函数和普通函数的区别(重点)
特性 | 箭头函数(=>) | 普通函数(function) |
---|---|---|
this 绑定 | 不绑定,继承外部作用域的 this |
根据调用方式动态绑定 |
构造函数 | 不能作为构造函数,不能使用 new |
可以作为构造函数 |
arguments | 没有 arguments 对象 |
有 arguments 对象 |
例如:
const obj = {
name: "Tom",
sayHi: function () {
console.log("Hello", this.name); // this.name 是 Tom
},
sayHiArrow: () => {
console.log("Hello", this.name); // this 指向外部(非 obj),所以是 undefined
}
};
obj.sayHi(); // Hello Tom
obj.sayHiArrow(); // Hello undefined
六、常见用途
- 简化函数写法(特别适合短函数)
写回调函数:
[1, 2, 3].map(x => x * 2);
- 避免 this 丢失的问题(常用于 React、类方法中)
如果你看到一个类似:
const greet: Greet = (name) => `Hello, ${name}`;
这表示:
Greet
是一个类型(通常是一个函数类型)- 右边是一个箭头函数,参数是
name
,返回一个字符串。