MST

星途 面试题库

面试题:TypeScript联合类型与交叉类型在变量声明中的复杂运用

假设有一个函数,它接受一个参数,这个参数可能是字符串类型的日期(格式为'YYYY - MM - DD')或者是Date类型的日期对象。请使用TypeScript的联合类型来定义该函数参数的类型,并在函数内部实现对这两种类型参数的正确处理,将日期格式化为'YYYY年MM月DD日'的字符串形式返回。另外,若要对这个参数类型添加一些额外的公共属性(例如都有一个表示时区的字符串属性'timezone'),如何使用交叉类型来实现?
28.6万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试
// 使用联合类型定义参数类型
function formatDate(date: string | Date): string {
    let d: Date;
    if (typeof date ==='string') {
        d = new Date(date);
    } else {
        d = date;
    }
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    return `${year}年${month}月${day}日`;
}

// 使用交叉类型添加公共属性
interface WithTimezone {
    timezone: string;
}

function formatDateWithTimezone(date: (string & WithTimezone) | (Date & WithTimezone)): string {
    let d: Date;
    if (typeof date ==='string') {
        d = new Date(date);
    } else {
        d = date;
    }
    const year = d.getFullYear();
    const month = String(d.getMonth() + 1).padStart(2, '0');
    const day = String(d.getDate()).padStart(2, '0');
    return `${year}年${month}月${day}日`;
}