MST

星途 面试题库

面试题:TypeScript 日期时间处理中联合类型与类型保护的应用

假设有一个函数 `processDateTime`,它接受一个参数,这个参数可能是 `Date` 类型,也可能是表示日期时间的字符串(格式为 'YYYY - MM - DD HH:MM:SS')。在函数内部,需要根据参数类型进行不同的处理,如果是 `Date` 类型,直接格式化输出;如果是字符串类型,先转换为 `Date` 类型再格式化输出。请用 TypeScript 实现该函数,并正确处理类型。
39.8万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
function processDateTime(input: Date | string): string {
    let date: Date;
    if (typeof input ==='string') {
        date = new Date(input);
    } else {
        date = input;
    }
    const year = date.getFullYear();
    const month = String(date.getMonth() + 1).padStart(2, '0');
    const day = String(date.getDate()).padStart(2, '0');
    const hours = String(date.getHours()).padStart(2, '0');
    const minutes = String(date.getMinutes()).padStart(2, '0');
    const seconds = String(date.getSeconds()).padStart(2, '0');
    return `${year}-${month}-${day} ${hours}:${minutes}:${seconds}`;
}