typescript学习:联合类型、交叉类型、可选属性和类型保护
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 函数时,会根据变量的类型来选择适当的计算方式。
标签:
typescript
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· DeepSeek 开源周回顾「GitHub 热点速览」
· 物流快递公司核心技术能力-地址解析分单基础技术分享
· .NET 10首个预览版发布:重大改进与新特性概览!
· AI与.NET技术实操系列(二):开始使用ML.NET
· .NET10 - 预览版1新功能体验(一)
2020-06-20 76. Minimum Window Substring
2020-06-20 424. Longest Repeating Character Replacement
2020-06-20 438. Find All Anagrams in a String
2020-06-20 961. N-Repeated Element in Size 2N Array
2019-06-20 203. Remove Linked List Elements