Skip to content

TypeScript 函数

函数是任何应用程序的基本构建块,用于执行特定的任务。在 TypeScript 中,我们可以为函数的参数和返回值添加类型,使函数更加健壮和易于理解。

定义函数

你可以使用函数声明或函数表达式来创建函数。

函数声明

typescript
// 命名函数
function add(x: number, y: number): number {
    return x + y;
}

函数表达式

typescript
// 匿名函数
const subtract = function(x: number, y: number): number {
    return x - y;
};

函数类型

我们可以为变量定义一个函数类型,这样它就只能持有一个符合该类型的函数。

typescript
let myAdd: (baseValue: number, increment: number) => number;

myAdd = function(x: number, y: number): number {
    return x + y;
};

// myAdd = function(a: string, b: string): string { return a + b; }; // Error

参数类型

1. 类型注解和类型推断

如上例所示,你可以为函数参数添加类型注解。返回值的类型也可以被注解。如果省略返回类型注解,TypeScript 会根据 return 语句尝试推断它。

typescript
function multiply(x: number, y: number) { // 返回类型被推断为 number
    return x * y;
}

2. 可选参数

在 TypeScript 中,函数的每个参数都被认为是必需的。但是,你可以在参数名后使用 ? 来标记其为可选参数。

可选参数必须在必需参数之后。

typescript
function buildName(firstName: string, lastName?: string): string {
    if (lastName) {
        return `${firstName} ${lastName}`;
    }
    return firstName;
}

let result1 = buildName("Bob"); // OK
let result2 = buildName("Bob", "Adams"); // OK
// let result3 = buildName("Bob", "Adams", "Sr."); // Error, too many parameters

3. 默认参数

你可以为参数设置一个默认值。当用户没有提供该参数或提供的值为 undefined 时,该参数会使用默认值。

typescript
function calculatePay(rate: number, hours: number = 40): number {
    return rate * hours;
}

let pay1 = calculatePay(25); // 25 * 40 = 1000
let pay2 = calculatePay(25, 30); // 25 * 30 = 750

与可选参数不同,带有默认值的参数不一定要放在必需参数之后。

4. 剩余参数 (Rest Parameters)

如果你需要处理多个参数作为一个组,或者你不知道一个函数最终会接收多少个参数,你可以使用剩余参数。它们会被收集到一个数组中。

typescript
function sum(...numbers: number[]): number {
    let total = 0;
    for (const num of numbers) {
        total += num;
    }
    return total;
}

console.log(sum(1, 2, 3)); // 6
console.log(sum(10, 20, 30, 40)); // 100

箭头函数 (Arrow Functions)

箭头函数是 ES6 中引入的一种更简洁的函数语法。它还解决了 this 关键字在传统函数中的指向问题。

语法

typescript
const numbers = [1, 2, 3, 4, 5];

// 传统函数
const squared1 = numbers.map(function(n) {
    return n * n;
});

// 箭头函数
const squared2 = numbers.map(n => n * n);

this 的行为

在箭头函数中,this 的值由函数创建时的上下文决定,而不是调用时的上下文。这在处理事件处理器或回调函数时非常有用。

typescript
class MyClass {
    value: number = 10;

    // 使用箭头函数作为方法
    start = () => {
        // 这里的 'this' 指向 MyClass 的实例
        setInterval(() => {
            console.log(this.value);
        }, 1000);
    }
}

let myInstance = new MyClass();
myInstance.start();

如果 start 是一个普通函数,setInterval 回调中的 this 将会是 window (在浏览器中) 或 undefined (在严格模式下),导致 this.value 出错。

本站内容仅供学习和研究使用。