面试题答案
一键面试函数重载基本语法结构
在TypeScript中,函数重载允许我们为同一个函数定义多个不同的函数签名。语法结构如下:
// 函数重载声明
function functionName(arg1: type1, arg2: type2): returnType1;
function functionName(arg1: otherType1, arg2: otherType2): returnType2;
// 函数实现
function functionName(arg1: any, arg2: any): any {
// 函数体逻辑,根据传入参数类型执行不同操作
}
在上述代码中,前面的多个声明就是函数重载,它们定义了函数不同的调用形式(参数类型和返回类型)。最后一个函数实现则是实际执行的代码,它需要兼容前面所有重载声明的参数类型。
函数重载应用示例
// 函数重载声明:数字相加
function calculate(a: number, b: number): number;
// 函数重载声明:字符串拼接
function calculate(a: string, b: string): string;
// 函数实现
function calculate(a: any, b: any): any {
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 argument types');
}
// 调用示例
const numResult = calculate(1, 2); // 返回数字 3
const strResult = calculate('Hello, ', 'world!'); // 返回字符串 'Hello, world!'
在这个示例中,calculate
函数有两个重载声明,一个用于数字相加,另一个用于字符串拼接。函数实现根据传入参数的类型来决定执行哪种操作。