TypeScript 箭头函数

// 1. 基础语法
// 普通函数
function add(a: number, b: number): number {
    return a + b;
}

// 转换为箭头函数
const addArrow = (a: number, b: number): number => {
    return a + b;
};

// 2. 单行返回值省略大括号和 return
const multiply = (a: number, b: number): number => a * b;

// 3. 单个参数省略括号
const square = (x: number): number => x * x;
// 更简洁写法
const squareSimple = x => x * x;

// 4. 无参数需要括号
const getRandom = (): number => Math.random();

// 5. 箭头函数与 this 绑定
class Counter {
    count: number = 0;
    // 使用箭头函数确保 this 指向实例
    increment = () => {
        this.count++;
    };
}

// 6. 泛型箭头函数
const identity = <T>(arg: T): T => arg;

// 7. 异步箭头函数
const fetchData = async (url: string): Promise<string> => {
    const response = await fetch(url);
    return response.text();
};

 

posted @ 2025-08-30 18:45  liessay  阅读(1)  评论(0)    收藏  举报