类型守卫
使用类型守卫安全地处理未知类型或 any 类型
类型守卫 是 CoddyKit 上的免费 TypeScript Academy 课时。 这是第 4 节课,共 4 节。 你可以在下方免费阅读本课时的完整内容 — 然后在浏览器中使用内置代码编辑器和全天候 AI 导师进行实践。 这是 TypeScript Academy 学习路径的一部分,你的进度在网页和 CoddyKit 应用中同步。 TypeScript Academy 课程共包含 4 节课。
类型守卫简介
类型守卫
欢迎来到下一课!本课将介绍类型守卫。这是 TypeScript 的一项强大功能,可以在运行时缩小类型范围。类型守卫能确保代码具有类型安全性,并避免错误。让我们开始吧!

什么是类型守卫?
什么是类型守卫?
类型守卫是一个函数或结构,用于在运行时确定变量的类型。它可以让 TypeScript 在特定代码块中缩小变量的类型范围。
示例:
任务:编写一个使用类型守卫检查值是否为数字的函数。
function isString(value: unknown): boolean {
return typeof value === "string";
}
function printLength(value: unknown): void {
if (isString(value)) {
console.log(value.length);
// TypeScript knows 'value' is a string here
} else {
console.log("Value is not a string");
}
}
printLength("Hello");
// Output: 5
printLength(42);
// Output: Value is not a string
使用类型运算符处理原始类型
使用 typeof 处理原始类型
您可以使用 typeof 运算符检查字符串、数字和布尔值等原始值的类型。
示例:
任务:使用 typeof 在函数中区分字符串和数字。
function printValue(value: string | number): void {
if (typeof value === "string") {
console.log(`String value: ${value}`);
} else {
console.log(`Number value: ${value}`);
}
}
printValue("Hello");
// Output: String value: Hello
printValue(42);
// Output: Number value: 42
使用实例关系检查处理类
使用 instanceof 处理类
instanceof 运算符会检查对象是否为特定类的实例。示例:
任务:使用 instanceof 在函数中处理不同的类实例。
class Dog {
bark(): void {
console.log("Woof!");
}
}
class Cat {
meow(): void {
console.log("Meow!");
}
}
function makeSound(animal: Dog | Cat): void {
if (animal instanceof Dog) {
animal.bark();
} else {
animal.meow();
}
}
let dog = new Dog();
let cat = new Cat();
makeSound(dog);
// Output: Woof!
makeSound(cat);
// Output: Meow!
使用自定义类型守卫
使用自定义类型守卫
您可以使用返回类型 value is Type 创建自定义类型守卫函数。示例:
interface Car {
make: string;
model: string;
}
interface Bike {
brand: string;
type: string;
}
function isCar(vehicle: Car | Bike): vehicle is Car {
return (vehicle as Car).make !== undefined;
}
function printVehicle(vehicle: Car | Bike): void {
if (isCar(vehicle)) {
console.log(`Car: ${vehicle.make} ${vehicle.model}`);
} else {
console.log(`Bike: ${vehicle.brand} ${vehicle.type}`);
}
}
let car: Car = { make: "Toyota", model: "Corolla" };
let bike: Bike = { brand: "Yamaha", type: "Sport" };
printVehicle(car);
// Output: Car: Toyota Corolla
printVehicle(bike);
// Output: Bike: Yamaha Sport
可辨识联合类型
可辨识联合类型
可辨识联合类型使用一个公共属性来区分不同的类型。示例:
interface Circle {
kind: "circle";
radius: number;
}
interface Rectangle {
kind: "rectangle";
width: number;
height: number;
}
type Shape = Circle | Rectangle;
function calculateArea(shape: Shape): number {
if (shape.kind === "circle") {
return Math.PI * shape.radius ** 2;
} else {
return shape.width * shape.height;
}
}
let circle: Circle = { kind: "circle", radius: 5 };
let rectangle: Rectangle = { kind: "rectangle", width: 10, height: 20 };
console.log(calculateArea(circle));
// Output: 78.53981633974483
console.log(calculateArea(rectangle));
// Output: 200
穷尽性检查
穷尽性检查
穷尽性检查可确保已处理可辨识联合类型中的所有可能情况。示例:
function getShapeInfo(shape: Shape): string {
switch (shape.kind) {
case "circle":
return `Circle with radius ${shape.radius}`;
case "rectangle":
return `Rectangle with dimensions ${shape.width}x${shape.height}`;
default:
// This line ensures all cases are handled
const _exhaustiveCheck: never = shape;
return _exhaustiveCheck;
}
}
常见错误
常见错误
使用类型守卫时,以下是一些常见错误:
- 忘记包含联合类型中的所有情况。
- 没有在条件逻辑的所有分支中使用类型守卫。
- 在没有适当检查的情况下,滥用
as转换类型。
提示:在访问类型的特定属性或方法之前,请始终使用类型守卫缩小类型范围!
做得好!
做得好!
恭喜您!您已经学会了如何在 TypeScript 中使用类型守卫,在运行时缩小类型范围并确保类型安全。类型守卫对于处理复杂的联合类型和创建健壮、无错误的代码至关重要。在下一课中,我们将探索高级映射类型。让我们继续编写代码吧!

常见问题解答
「类型守卫」课时是免费的吗?
是的 — 「类型守卫」的完整文本可在网页上免费阅读。要进行交互式练习(内置代码编辑器和全天候 AI 导师)并解锁 TypeScript Academy 课程的其余内容,请升级到 CoddyKit PRO。 TypeScript Academy 课程共包含 4 节课。
「类型守卫」这节课中我会学到什么?
使用类型守卫安全地处理未知类型或 any 类型 你通过在浏览器中直接运行的动手代码来练习 TypeScript Academy,全天候 AI 导师会在你学习这节课的过程中回答你的问题。
学习 TypeScript Academy 需要有经验吗?
无需任何先前经验。CoddyKit 上的 TypeScript Academy 课程适合初学者到高级学习者,你可以从这里开始或从头开始,按照自己的节奏学习。 这是第 4 节课,共 4 节。
「类型守卫」课时需要多长时间?
大多数 CoddyKit 课程大约需要 5–10 分钟。每节课都很精短且互动,所以你能稳步进步,并在网页和应用中从离开的地方继续。
我能在这节 TypeScript Academy 课中编写并运行代码吗?
能。每节 TypeScript Academy 课都包含内置代码编辑器,你可以在浏览器中直接编写并运行真实代码,并获得即时 AI 反馈 — 无需本地设置。