面试题答案
一键面试函数重载的使用场景
在TypeScript中,函数重载主要用于当一个函数需要根据不同的参数类型或数量执行不同的逻辑,并返回不同类型的结果时。比如在一个图形绘制库中,可能有一个 draw
函数,它既可以接收 Circle
对象绘制圆形,也可以接收 Rectangle
对象绘制矩形,根据传入对象类型不同执行不同绘制逻辑。
示例代码
// 函数重载声明
function add(a: number, b: number): number;
function add(a: string, b: string): string;
// 函数实现
function add(a: any, b: any): any {
if (typeof a === 'number' && typeof b === 'number') {
return a + b;
}
if (typeof a ==='string' && typeof b ==='string') {
return a + b;
}
throw new Error('Unsupported argument types');
}
// 调用
const numResult = add(1, 2);
const strResult = add('Hello, ', 'world');
console.log(numResult);
console.log(strResult);