TypeScript 的高级类型提供了更丰富的方式来描述变量或函数的类型,进而增强了代码的强类型检查和可读性。以下是一些常见的高级类型:
-
联合类型(Union Types): 联合类型允许一个变量是多种类型中的一种。比如,
number | string
表示变量可以是number
或者string
类型。示例:
typescriptfunction printId(id: number | string) { console.log(`Your ID is: ${id}`); }
-
交叉类型(Intersection Types): 交叉类型是将多个类型合并为一个类型,这意味着你可以把多个类型的属性合并到一起。
示例:
typescripttype Employee = { name: string; startDate: Date; }; type Manager = Employee & { group: string; }; let manager: Manager = { name: "Alice", startDate: new Date(), group: "Sales" };
-
类型别名(Type Aliases): 类型别名允许你给一个类型一个新的名字。这使得类型更易于重用和引用。
示例:
typescripttype Point = { x: number; y: number; }; function printCoord(pt: Point) { console.log(`The coordinate's x value: ${pt.x}`); console.log(`The coordinate's y value: ${pt.y}`); }
-
可辨识联合(Discriminated Unions): 可辨识联合是一种模式,它结合了联合类型和字面量类型的特点,常用于实现类型安全的状态或对象的变种。
示例:
typescriptinterface Square { kind: "square"; size: number; } interface Rectangle { kind: "rectangle"; width: number; height: number; } type Shape = Square | Rectangle; function area(s: Shape) { switch (s.kind) { case "square": return s.size * s.size; case "rectangle": return s.width * s.height; } }
-
泛型(Generics): 泛型提供了一种方法来创建可重用的组件,这些组件可以支持多种类型而不失类型的安全性。
示例:
typescriptfunction identity<T>(arg: T): T { return arg; } let output = identity<string>("myString"); let outputNumber = identity<number>(100);
这些高级类型不仅可以提高代码的灵活性和可重用性,而且还可以帮助开发者在编译时捕捉到更多的错误,从而提高应用程序的稳定性和质量。
2024年8月2日 13:51 回复