TypeScript4(函数)

46 阅读1分钟

在 TypeScript(TS)中,函数的写法和使用场景非常丰富,它在 JavaScript 的基础上增加了类型检查,让代码更加健壮和可维护。

1.普通函数

和js类似,但可以为参数和返回值添加类型注解。

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

2.函数表达式

将函数赋值给一个变量。

const multiply = function (x: number, y: number): number {
  return x * y;
};

3.箭头函数

es6引入的简洁语法,在ts中也广泛使用。

const add = (a: number, b: number): number => {
    return a + b;
}

4.可选参数和默认参数

(1)可选参数:使用?标记,代表这个参数可传可不传。

function greet(name: string, age?: number): string {
  if (age) {
    return `Hello, ${name}! You are ${age} years old.`;
  }
  return `Hello, ${name}!`;
}

console.log(greet('Alice')); // 输出: Hello, Alice!
console.log(greet('Bob', 30)); // 输出: Hello, Bob! You are 30 years old.

(2)默认参数:为参数设置默认值,如果调用时没有传递该参数,则使用默认值。

function greet(name: string, age: number = 25): string {
  return `Hello, ${name}! You are ${age} years old.`;
}

console.log(greet('Charlie')); // 输出: Hello, Charlie! You are 25 years old.
console.log(greet('David', 40)); // 输出: Hello, David! You are 40 years old.

5.剩余参数

使用...语法,将不定量的参数收集到一个数组中。

function sumAll(...numbers: number[]): number {
  return numbers.reduce((total, num) => total + num, 0);
}

console.log(sumAll(1, 2, 3)); // 输出: 6
console.log(sumAll(10, 20, 30, 40)); // 输出: 100

6.函数重载

TS 允许为同一个函数提供多个函数签名(签名只包含参数类型和返回值类型),以处理不同参数类型或数量的调用。但函数重载的实现只写一次

// 函数签名
function reverse(x: number): number;
function reverse(x: string): string;
// 函数实现
function reverse(x: number | string): number | string {
  if (typeof x === 'number') {
    return Number(String(x).split('').reverse().join(''));
  } else {
    return x.split('').reverse().join('');
  }
}

console.log(reverse(123)); // 输出: 321
console.log(reverse('hello')); // 输出: olleh

举个栗子,时间处理函数。

// 重载签名:定义了函数可以接受的不同参数类型。
function formatDate(date: Date): string;
function formatDate(timestamp: number): string;
function formatDate(dateString: string): string;

// 函数实现:它使用联合类型(any 或 unknown)来兼容所有重载签名。
// 包含类型守卫(type guards)来处理不同类型的输入。
function formatDate(input: Date | number | string): string {
    let date: Date;

    //处理输入
    if (input instanceof Date) {
        // 如果输入是 Date 对象
        date = input;
    } else if (typeof input === 'number') {
        // 如果输入是数字(时间戳)
        date = new Date(input);
    } else if (typeof input === 'string') {
        // 如果输入是字符串
        date = new Date(input);
    } else {
        // 处理所有不匹配的情况
        throw new Error('Invalid input type. Expected Date, number, or string.');
    }

    // 检查解析后的日期是否有效
    if (isNaN(date.getTime())) {
        throw new Error('Invalid date format.');
    }

    // 格式化日期为 'YYYY-MM-DD' 格式
    const year = date.getFullYear();
    const month = (date.getMonth() + 1).toString().padStart(2, '0');
    const day = date.getDate().toString().padStart(2, '0');

    return `${year}-${month}-${day}`;
}

// 示例用法
const today = new Date();
const timestamp = 1672531200000; // 2023-01-01
const dateStr = '2024-05-20T10:00:00Z';

console.log("日期 " + formatDate(today));        // 输出:例如 '2025-08-16'
console.log("时间戳 " + formatDate(timestamp));    // 输出:'2023-01-01'
console.log("字符串 " + formatDate(dateStr));      // 输出:'2024-05-20'
// console.log(formatDate(true));      // 编译时会报错,因为它不匹配任何重载签名
// console.log(formatDate('invalid-date')); // 运行时会报错

参考文章

小满zs 学习typeScript5(函数扩展) xiaoman.blog.csdn.net/article/det…