1. 联合类型(Union Types)
联合类型是指将多个类型组合成一个类型,表示这个类型可以取这些类型中的任意一种。在 TypeScript 中,可以使用竖线 | 作为联合类型的分隔符,例如:
let myVar: string | number; myVar = "hello"; // 合法 myVar = 123; // 合法 myVar = true; // 错误
2. 交叉类型(Intersection Types)
交叉类型是指将多个类型组合在一起,表示这个类型包含了这些类型的所有特征。在 TypeScript 中,可以使用 & 符号作为交叉类型的分隔符,例如:
interface A { a: string; } interface B { b: number; } type C = A & B; const myVar: C = { a: "hello", b: 123, };
3. 可选属性(Optional Properties)
在 TypeScript 中,我们可以使用 ? 符号来表示一个属性是可选的。例如:
interface User { name: string; age?: number; } const user1: User = { name: "Alice" }; // 合法 const user2: User = { name: "Bob", age: 20 }; // 合法 const user3: User = { age: 20 }; // 错误,缺少 name 属性
上述代码中,age 属性是可选的,因此在创建 User 类型变量时可以不赋值。
4. 类型保护(Type Guards)
在 TypeScript 中,类型保护是指一些用于判断变量类型的机制,可以根据判断结果来确定变量的类型。类型保护的使用可以避免一些运行时类型错误的问题。
常见的类型保护包括以下几种:
- typeof 操作符:可以使用 typeof 操作符来判断一个变量的类型,例如:
function logUser(user: string | number) { if (typeof user === "string") { console.log(`User name is ${user}`); } else { console.log(`User ID is ${user}`); } } //instanceof 操作符:可以使用 instanceof 操作符来判断一个对象是否属于某个类或其派生类,例如: class Car { drive() { console.log("Driving..."); } } class Truck { moveCargo() { console.log("Moving cargo..."); } } function driveVehicle(vehicle: Car | Truck) { if (vehicle instanceof Car) { vehicle.drive(); } else { vehicle.moveCargo(); } }
- 自定义类型保护函数:可以定义一个自定义函数来判断一个变量是否属于某个特定类型。例如:
interface Circle { kind: "circle"; radius: number; } interface Rectangle { kind: "rectangle"; width: number; height: number; } type Shape = Circle | Rectangle; // 自定义类型保护函数 function isCircle(shape: Shape): shape is Circle { return shape.kind === "circle"; } // 使用自定义类型保护函数 function getArea(shape: Shape) { if (isCircle(shape)) { return Math.PI * shape.radius ** 2; } else { return shape.width * shape.height; } }
上述代码中,我们定义了一个自定义类型保护函数 isCircle,用于判断一个变量是否属于 Circle 类型。在调用 getArea 函数时,会根据变量的类型来选择适当的计算方式。