面试题答案
一键面试假设使用 TypeScript 来优化和扩展:
// 假设 customDateTimeLib 已经被导入
import customDateTimeLib from 'customDateTimeLib';
// 优化原 addDays 函数的类型定义
interface DateLike {
getFullYear(): number;
getMonth(): number;
getDate(): number;
getHours(): number;
getMinutes(): number;
getSeconds(): number;
}
function addDays(date: DateLike, days: number): Date {
let newDate = new Date(date.getTime());
newDate.setDate(newDate.getDate() + days);
return newDate;
}
// 扩展新功能
function addDaysFromString(dateStr: string, days: number): Date {
const date = new Date(dateStr);
return addDays(date, days);
}
// 完善新功能的类型定义
interface CustomDateTimeLib {
addDays: (date: DateLike, days: number) => Date;
addDaysFromString: (dateStr: string, days: number) => Date;
}
// 假设 customDateTimeLib 已经有 addDays 函数,现在扩展 addDaysFromString 并完善类型
customDateTimeLib.addDays = addDays;
customDateTimeLib.addDaysFromString = addDaysFromString;
export default customDateTimeLib as CustomDateTimeLib;
在上述代码中:
- 首先定义了
DateLike
接口,用于更明确地描述addDays
函数第一个参数的类型。 - 优化了
addDays
函数的类型定义。 - 扩展了
addDaysFromString
函数,接受日期时间字符串并调用addDays
函数返回结果。 - 定义了
CustomDateTimeLib
接口,用于描述库的整体类型,包含新扩展的函数及其类型定义,并将库对象断言为该类型。