JavaScript / TypeScript / 系统课时
typeof 类型保护
typeof 类型保护
本课解决联合类型在分支中无法直接调用专属能力的问题。你将使用 typeof 完成运行时判断,让 TypeScript 自动收窄类型,并掌握 null、数组等常见边界。
学习目标
- 使用
typeof对基础类型进行收窄 - 在不同分支中安全访问类型专属成员
- 识别
null和数组判断中的特殊情况
使用 typeof 收窄类型
typeof 是 JavaScript 提供的运行时运算符。TypeScript 会分析常见判断条件,并在对应分支中缩小联合类型范围。
ts
function formatInput(value: string | number): string {
if (typeof value === "string") {
return value.trim().toUpperCase();
}
return value.toFixed(2);
}
console.log(formatInput(" typescript "));
console.log(formatInput(18));预期输出
text
TYPESCRIPT
18.00进入第一个分支时,value 会被收窄为 string,因此可以调用字符串方法;离开该分支后,TypeScript 知道剩余情况只能是 number。
识别 typeof 支持的运行时类型
typeof 能识别 string、number、boolean、bigint、symbol、undefined、object 和 function。它判断的是 JavaScript 运行时结果,而不是 TypeScript 的接口或泛型信息。
ts
function describe(value: string | (() => void)): string {
if (typeof value === "function") {
return "这是函数";
}
return "字符串长度:" + value.length;
}
console.log(describe(() => undefined));
console.log(describe("TS"));预期输出
text
这是函数
字符串长度:2typeof 适合判断基础类型和函数。对于接口、对象字段结构或数组元素类型,需要使用其他类型保护方式。
处理 null 与 object 边界
JavaScript 中存在特殊情况:typeof null 的结果是 "object"。因此判断对象时,通常需要同时排除 null。
ts
function getName(value: { name: string } | null): string {
if (typeof value === "object" && value !== null) {
return value.name;
}
return "未知";
}
console.log(getName({ name: "小林" }));
console.log(getName(null));预期输出
text
小林
未知这里利用 && 的短路特性,只有前一个条件确认对象类型后,才继续检查 value !== null 并访问属性。
判断数组时不要使用 typeof
数组在 JavaScript 中也是对象,所以 typeof [] 返回 "object"。判断数组应该使用 Array.isArray,TypeScript 也能根据该判断自动完成收窄。
ts
function count(value: string | string[]): number {
if (Array.isArray(value)) {
return value.length;
}
return value.length;
}
console.log(count(["a", "b", "c"]));
console.log(count("TypeScript"));预期输出
text
3
10两个分支虽然都读取 length,但含义不同:数组返回元素数量,字符串返回字符数量。实际开发中应根据运行时类型选择对应判断方式,而不是依赖 object 这种宽泛结果。
按自己的节奏,确认真正理解。