在TypeScript中,泛型是一种允许你编写可重用的代码,同时适应各种类型的强大工具。
泛型的主要目标是提高类型安全性和代码重用性,同时保持类型的明确性。
以下是一些具体的使用例子:
泛型函数:你可以定义一个接受某种类型参数的函数,然后这个函数可以操作那个类型的任何值。例如:
- typescriptfunction printValue<T>(value: T): void {
- console.log(value);
- }
-
- printValue(10); // 输出:10
- printValue("Hello"); // 输出:"Hello"
泛型类:你可以定义一个类,该类的类型参数可以是任何类型。例如:
- typescriptclass Box<T> {
- content: T;
-
- constructor(value: T) {
- this.content = value;
- }
-
- getValue(): T {
- return this.content;
- }
- }
-
- let integerBox = new Box<number>(10);
- let stringBox = new Box<string>("Hello");
-
- console.log(integerBox.getValue()); // 输出:10
- console.log(stringBox.getValue()); // 输出:"Hello"
泛型接口:你可以定义一个接口,该接口的类型参数可以是任何类型。例如:
- typescriptinterface BoxInterface<T> {
- content: T;
- getValue(): T;
- }
-
- class Box<T> implements BoxInterface<T> {
- content: T;
-
- constructor(value: T) {
- this.content = value;
- }
-
- getValue(): T {
- return this.content;
- }
- }
以上的 就是泛型标记,表示这个类、函数或接口是泛型的,可以接受一个或多个类型参数。使用时可以用实际的类型来替代 ,如 、 等。
在TypeScript中,泛型约束是一种限制泛型类型参数的方式,以便更精确地指定泛型代码的适用范围。
泛型约束可以通过在泛型类型参数后面添加一个约束类型来实现。约束类型可以是一个内置类型、一个类类型或者一个接口类型。
以下是一些泛型约束的使用例子:
约束为内置类型:你可以约束泛型类型参数为某些内置类型。例如:
- typescriptfunction printValue(value: number | string): void {
- console.log(value);
- }
在这个例子中,printValue 函数的泛型类型参数被约束为 number 或 string 类型。约束为类类型:你可以约束泛型类型参数为一个类类型。例如:
- typescriptclass Animal {
- speak(): void {
- console.log("Animal speaks");
- }
- }
-
- function printValue(value: Animal): void {
- console.log(value);
- }
在这个例子中,printValue 函数的泛型类型参数被约束为 Animal 类类型。
约束为接口类型:你可以约束泛型类型参数为一个接口类型。例如:
- typescriptinterface Shape {
- area(): number;
- }
-
- function printValue(value: Shape): void {
- console.log(value);
- }
在这个例子中,printValue 函数的泛型类型参数被约束为 Shape 接口类型。
通过使用泛型约束,你可以确保泛型代码适用于特定类型的值,并且可以在编译时捕获潜在的类型错误。