1. 场景举例
- DOM 操作场景:当从
document.getElementById
获取元素时,TypeScript 只能推断其返回类型为 HTMLElement | null
。例如:
const el = document.getElementById('myDiv');
// 如果确定页面上一定存在该元素,可以使用类型断言
const div = el as HTMLDivElement;
div.textContent = 'Hello';
- 函数返回值场景:假设调用一个返回值类型宽泛的函数,比如
JSON.parse
,其返回值类型为 any
。
const jsonStr = '{"name":"John"}';
const data = JSON.parse(jsonStr);
// 可以使用类型断言来指定具体类型
const user = data as { name: string };
console.log(user.name);
2. 避免使用不安全类型断言的方法
- 优化类型定义:
- 针对 DOM 操作:可以通过自定义类型守卫函数来安全地获取元素。
function getElement<T extends keyof HTMLElementTagNameMap>(id: string): T extends 'div'
? HTMLDivElement
: T extends 'p'
? HTMLParagraphElement
: HTMLElement | null {
const el = document.getElementById(id);
return el as any;
}
const div = getElement<"div">('myDiv');
if (div) {
div.textContent = 'Hello';
}
- **针对函数返回值**:可以使用泛型来约束 `JSON.parse` 的返回类型。
function safeParse<T>(jsonStr: string): T | null {
try {
return JSON.parse(jsonStr) as T;
} catch (e) {
return null;
}
}
const jsonStr = '{"name":"John"}';
const user = safeParse<{ name: string }>(jsonStr);
if (user) {
console.log(user.name);
}
- 使用类型推断:在很多情况下,TypeScript 能够根据上下文自动推断类型,不需要手动进行类型断言。例如,使用函数重载来让编译器正确推断返回类型。
function add(a: number, b: number): number;
function add(a: string, b: string): string;
function add(a: any, b: any): any {
return a + b;
}
const numResult = add(1, 2);
const strResult = add('a', 'b');