面试题答案
一键面试function printMessage(type: 'error', message: string): void;
function printMessage(type: 'warning', message: string): void;
function printMessage(type: 'info', message: string): void;
function printMessage(type: 'error' | 'warning' | 'info', message: string): void {
if (type === 'error') {
console.error(`Error: ${message}`);
// 记录到日志文件的逻辑,例如:
// const fs = require('fs');
// fs.appendFileSync('error.log', `Error: ${message}\n`);
} else if (type === 'warning') {
console.warn(`Warning: ${message}`);
} else if (type === 'info') {
console.log(`Info: ${message}`);
}
}
为什么使用函数重载而不是简单的if - else判断:
- 类型安全性:函数重载利用TypeScript的类型系统,在编译时就能确保传入的类型是正确的。例如,如果误传入了一个其他字符串,编译器会报错,而if - else判断只有在运行时才能发现错误。
- 代码可读性:函数重载在声明处就明确了不同类型参数对应的行为,代码阅读者可以直观地了解到该函数根据不同类型执行不同操作,而if - else判断可能需要深入到函数内部去理解逻辑。
- 可维护性:当需要添加新的字符串类型时,使用函数重载只需要在函数声明处添加新的重载定义,而if - else判断则需要在函数内部添加新的判断分支,可能影响原有的逻辑结构。