类型断言常见使用场景
- 绕过类型检查:当你确定某个值的类型,但 TypeScript 无法自动推断时,可使用类型断言绕过检查。例如从
document.getElementById
获取 DOM 元素,TypeScript 推断为 HTMLElement | null
,若确定元素存在,可断言其类型。
- 函数参数类型转换:在调用函数时,如果参数类型与函数定义不完全匹配,但你知道实际类型是兼容的,可通过类型断言使调用通过类型检查。
- 联合类型细化:当一个变量是联合类型,需要在特定逻辑分支中明确其具体类型时,使用类型断言。
类型断言方式及代码示例
- “尖括号”语法
let someValue: any = "this is a string";
let strLength: number = (<string>someValue).length;
as
语法
let someValue: any = "this is a string";
let strLength: number = (someValue as string).length;
- 在 DOM 操作中的应用(
as
语法)
// 获取元素,TypeScript 推断为 HTMLElement | null
const myElement = document.getElementById('myElement');
if (myElement) {
// 断言为 HTMLInputElement 类型
const inputElement = myElement as HTMLInputElement;
inputElement.value = 'Some value';
}
- 联合类型细化(尖括号语法)
function printValue(value: string | number) {
if (typeof value ==='string') {
let str = <string>value;
console.log(str.length);
} else {
let num = <number>value;
console.log(num.toFixed(2));
}
}