TypeScript 箭头函数
TypeScript 数组 

TypeScript 函数重载

在 TypeScript 中,函数重载(function overloading)允许我们定义多个同名函数签名,但这些函数签名具有不同的参数类型或数量。当调用这个函数时,TypeScript 编译器会根据传入参数的类型和数量来确定调用哪个重载版本。

函数重载实现步骤

  • 声明函数

  • 实现函数

函数重载举例

function add(a: number, b: number): number;

function add(a: string, b: string): string;

function add(a: string, b: string, c: string): string;

function add(a: any, b: any, c?: any): any {

    if (typeof a === 'number' && typeof b === 'number') {

        return a + b;

    } 
	else if(c) {
		return a.concat(b).concat(c);
	}
	else if (typeof a === 'string' && typeof b === 'string') {

        return a.concat(b);

    } else {
        throw new Error('Unsupported parameter types');
    }
}


// 调用重载的函数
console.log(add(1, 2)); // 输出 3

console.log(add('Hello', 'TypeScript')); // 输出 "HelloTypeScript"

console.log(add('Hello', ' TypeScript', ' how are you')); // 输出 "Hello TypeScript how are you"


在上面的例子中,第一个、第二个函数参数个数一样,但是类型不一样,第二个、第三个函数参数相同,但是参数个数不同。

使用总结

  • 重载的实现体函数必须在所有重载签名之后定义。

  • 实现体函数的参数类型可以是更宽泛的类型(如 any),但应能处理所有重载可能的情况。

  • 如果实现体函数不匹配任何重载签名,TypeScript 编译器会报错。


通过使用函数重载,我们可以提高代码的可读性和类型安全性,确保函数的行为符合预期并能够处理多种类型的输入。