MST

星途 面试题库

面试题:TypeScript 联合类型的应用场景

请举例说明 TypeScript 联合类型在实际前端开发中的两个常见应用场景,并编写相应代码示例。
31.2万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

场景一:函数参数接受多种类型

在前端开发中,一个函数可能需要接受不同类型的参数。例如,我们有一个函数用于显示文本,这个文本可能是字符串,也可能是数字。

function displayText(text: string | number) {
    if (typeof text ==='string') {
        console.log(text.toUpperCase());
    } else {
        console.log(text.toString());
    }
}

displayText('hello'); 
displayText(123); 

场景二:DOM 操作中元素类型判断

当我们获取 DOM 元素时,不同的选择器可能返回不同类型的元素。比如 getElementById 可能返回 HTMLElement 或者 null

function changeBackgroundColor(elementId: string, color: string) {
    const element: HTMLElement | null = document.getElementById(elementId);
    if (element) {
        element.style.backgroundColor = color;
    }
}

changeBackgroundColor('myDiv', 'blue');