MST
星途 面试题库

面试题:TypeScript 中类型保护与类型断言的区别及应用场景

阐述类型保护与类型断言在TypeScript中的概念、区别,分别列举至少两个应用场景,并通过代码示例说明。
40.7万 热度难度
前端开发TypeScript

知识考点

AI 面试

面试题答案

一键面试

类型保护

  1. 概念:类型保护是一种在运行时检查类型的机制,通过特定的语法和逻辑,TypeScript 能够在特定的代码块内确定变量的具体类型,从而使类型检查器能够应用更精确的类型定义。
  2. 区别:与类型断言不同,类型保护是基于运行时的实际检查来确定类型,而类型断言是开发者手动告知编译器某个变量的类型,不进行运行时检查。
  3. 应用场景
    • 检查函数参数类型
function printValue(value: string | number) {
    if (typeof value ==='string') {
        console.log(value.length);
    } else {
        console.log(value.toFixed(2));
    }
}
printValue('hello');
printValue(123);
- **检查数组元素类型**:
function processArray(arr: (string | number)[]) {
    arr.forEach((element) => {
        if (typeof element ==='string') {
            console.log(element.toUpperCase());
        } else {
            console.log(element * 2);
        }
    });
}
processArray(['a', 2]);

类型断言

  1. 概念:类型断言是一种语法,允许开发者手动指定一个值的类型,向编译器“断言”某个值具有特定的类型,绕过编译器的部分类型检查。
  2. 区别:不进行运行时检查,只是给编译器一个提示,让它按照开发者指定的类型处理,若实际类型与断言不符,可能导致运行时错误。
  3. 应用场景
    • 调用可能返回 null 的函数并确定返回值类型
function getElementById(id: string): HTMLElement | null {
    return document.getElementById(id);
}
const myElement = getElementById('myId') as HTMLElement;
myElement.style.color ='red';
- **将 `any` 类型转换为更具体的类型**:
let data: any = 'hello';
let strLength: number = (data as string).length;
console.log(strLength);