函数重载:(Function Overloading)是指在同一个作用域内,可以定义多个同名的函数,但这些函数的参数类型或参数个数必须不同。
function getValue(arg: number): number; function getValue(arg: string): string; function getValue(arg: number | string): number | string { if (typeof arg === 'number') { return arg * 2; } else if (typeof arg === 'string') { return arg.toUpperCase(); } } console.log(getValue(10)); // 输出: 20 console.log(getValue('hello')); // 输出: "HELLO"
函数重载的目的是为了提供更便捷的函数调用方式,让函数在处理不同类型或数量的参数时能够有不同的行为。