类型断言与类型守卫
类型断言为编译器指定一个兼容的类型,不执行运行时检查;类型守卫通过实际判断,让编译器在对应分支中缩小类型范围。
类型断言
const value: unknown = 'hello';
const length = (value as string).length;
也可以写成 (<string>value).length,但尖括号断言语法不能用于 .tsx 文件。as 写法在 .ts 和 .tsx 中均可使用。
断言不会转换值,也不会验证内容。as number 不等同于 Number(value);如果数据不符合断言,后续操作仍可能在运行时报错。
DOM 元素类型
const input = document.getElementById('myInput') as HTMLInputElement | null;
console.log(input?.value);
这保留了元素可能不存在的情况,但仍假设它确实是输入框。需要验证时,可以使用 instanceof:
const element = document.getElementById('search');
if (element instanceof HTMLInputElement) {
console.log(element.value);
}
非空断言
function getLength(text: string | null): number {
return text!.length;
}
! 只从类型中移除 null、undefined,不会检查值。上例传入 null 会报错;可以通过空值判断或 text?.length ?? 0 避免断言。
不要用 {} as User 隐藏尚未完成的初始化。若对象确实处于构建过程,可用 Partial<User> 表达这一状态,并在完成后验证必需属性。
内置类型守卫
typeof:区分原始类型
function format(value: string | number): string {
if (typeof value === 'string') {
return value.toUpperCase();
}
return value.toFixed(2);
}
判断对象时还需排除 null,因为 typeof null === 'object'。
instanceof:区分类实例
function formatDate(value: Date | string): string {
return value instanceof Date ? value.toISOString() : value;
}
in:检查属性是否存在
interface Admin {
role: string;
}
interface Member {
email: string;
}
function describe(account: Admin | Member): string {
if ('role' in account) {
return account.role;
}
return account.email;
}
in 也会检查原型链上的属性。对于可选属性,仅凭存在性未必能把联合类型完全分开,也不能保证属性值符合预期类型。
自定义类型守卫
使用类型谓词 parameter is Type,让检查结果参与类型缩小:
interface User {
id: number;
name: string;
}
function isUser(value: unknown): value is User {
return (
typeof value === 'object' &&
value !== null &&
'id' in value &&
typeof value.id === 'number' &&
'name' in value &&
typeof value.name === 'string'
);
}
function greetUser(value: unknown): string {
return isUser(value) ? `Hello, ${value.name}` : 'Invalid user';
}
编译器依赖类型谓词的声明,不会证明检查逻辑完整。验证外部数据时,需同时检查必需字段及其值类型,不能只判断字段存在。
可辨识联合类型
让每个成员拥有同一个属性、不同的字面量值,可以直接按该属性缩小类型:
type Result =
| { status: 'success'; data: string }
| { status: 'error'; message: string };
function handleResult(result: Result): string {
if (result.status === 'success') {
return result.data;
}
return result.message;
}
编译器能通过控制流确定类型时,无需再添加 as。需要在校验失败时中断执行,并在调用后缩小类型时,见 asserts 断言函数与穷尽检查。