// 函数重载声明
function add(a: number, b: number): number;
function add(a: string, b: string): string;
// 函数实现
function add(a: number | string, b: number | string): number | string {
if (typeof a === 'number' && typeof b === 'number') {
return a + b;
} else if (typeof a ==='string' && typeof b ==='string') {
return a + b;
}
throw new Error('参数类型不匹配');
}
// 调用示例
const sumResult: number = add(1, 2);
const concatResult: string = add('Hello, ', 'world');
console.log(sumResult); // 输出: 3
console.log(concatResult); // 输出: Hello, world