// 函数重载声明1:接受两个数字参数,返回数字
function add(a: number, b: number): number;
// 函数重载声明2:接受两个字符串参数,返回字符串
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('Unsupported parameter types');
}
// 使用示例
const numResult = add(1, 2);
const strResult = add('Hello, ', 'world');