类型系统
类型断言与类型守卫
掌握 as 断言、typeof/instanceof 类型守卫
类型断言与类型守卫
类型断言告诉编译器"相信我",类型守卫则让编译器自己推导。
学完本章你将: 掌握 as、typeof、instanceof、自定义守卫。
类型断言
typescript
// as 语法(推荐)
let value: unknown = "hello";
let length: number = (value as string).length;
// 尖括号语法(JSX 中不能用)
let length2: number = (<string>value).length;
// DOM 断言
const canvas = document.getElementById("myCanvas") as HTMLCanvasElement;
const ctx = canvas.getContext("2d")!; // ! 非空断言
// 双重断言(谨慎使用)
let data: string = (42 as unknown as string);
typeof 类型守卫
typescript
function process(value: string | number | boolean): string {
if (typeof value === "string") {
return value.toUpperCase(); // string
}
if (typeof value === "number") {
return value.toFixed(2); // number
}
return value.toString(); // boolean
}
// null 检查
function printLength(value: string | null): void {
if (value) {
console.log(value.length); // string(非 null)
}
}
instanceof 类型守卫
typescript
class Dog {
bark() { return "汪汪"; }
}
class Cat {
meow() { return "喵喵"; }
}
function makeSound(animal: Dog | Cat): string {
if (animal instanceof Dog) {
return animal.bark(); // Dog
}
return animal.meow(); // Cat
}
自定义类型守卫
typescript
interface Fish { swim(): void; }
interface Bird { fly(): void; }
// 自定义类型守卫:返回 animal is Fish
function isFish(animal: Fish | Bird): animal is Fish {
return (animal as Fish).swim !== undefined;
}
function move(animal: Fish | Bird): void {
if (isFish(animal)) {
animal.swim(); // Fish ✅
} else {
animal.fly(); // Bird ✅
}
}
// Array.filter 结合守卫
const values: (string | number)[] = ["a", 1, "b", 2];
const strings: string[] = values.filter(
(v): v is string => typeof v === "string"
);
console.log(strings); // ["a", "b"]