类型保护
- 概念:类型保护是一种在运行时检查类型的机制,通过特定的语法和逻辑,TypeScript 能够在特定的代码块内确定变量的具体类型,从而使类型检查器能够应用更精确的类型定义。
- 区别:与类型断言不同,类型保护是基于运行时的实际检查来确定类型,而类型断言是开发者手动告知编译器某个变量的类型,不进行运行时检查。
- 应用场景:
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]);
类型断言
- 概念:类型断言是一种语法,允许开发者手动指定一个值的类型,向编译器“断言”某个值具有特定的类型,绕过编译器的部分类型检查。
- 区别:不进行运行时检查,只是给编译器一个提示,让它按照开发者指定的类型处理,若实际类型与断言不符,可能导致运行时错误。
- 应用场景:
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);