面试题答案
一键面试场景一:函数参数接受多种类型
在前端开发中,一个函数可能需要接受不同类型的参数。例如,我们有一个函数用于显示文本,这个文本可能是字符串,也可能是数字。
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');