TypeScript 泛型(Generics)

131 阅读1分钟

在TypeScript中,泛型(Generics)是一种用于创建可重用代码的强大工具。它允许在定义类、函数或接口时使用类型参数,以便在使用时指定具体的类型。

通过使用泛型,可以编写更通用、灵活和类型安全的代码。使用泛型可以实现类型的参数化,

在多个地方重用同一段代码,而不必为每种类型都编写重复的代码。这样可以增加代码的可维护性和复用性。

在TypeScript中,泛型可以用于多种情况,比如:

  1. 函数泛型:可以在函数定义中使用泛型来表示参数或返回值的类型。
function printArray<T>(arr: T[]): void {
  for (let item of arr) {
    console.log(item);
  }
}

// 使用泛型函数
printArray<number>([1, 2, 3]); // 打印 1 2 3
printArray<string>(['a', 'b', 'c']); // 打印 a b c
  1. 类泛型:可以在类的定义中使用泛型来表示类的成员变量或方法的参数类型。
class Box<T> {
  private value: T;

  constructor(value: T) {
    this.value = value;
  }

  getValue(): T {
    return this.value;
  }
}

// 使用泛型类
const box1 = new Box<number>(10);
console.log(box1.getValue()); // 输出 10

const box2 = new Box<string>('Hello');
console.log(box2.getValue()); // 输出 Hello
  1. 接口泛型:可以在接口定义中使用泛型来表示接口中方法的参数类型或返回值类型。
interface List<T> {
  add(item: T): void;
  get(index: number): T;
}

class TodoList<T> implements List<T> {
  private items: T[] = [];

  add(item: T): void {
    this.items.push(item);
  }

  get(index: number): T {
    return this.items[index];
  }
}

// 使用泛型接口
const todoList = new TodoList<string>();
todoList.add('Do laundry');
todoList.add('Buy groceries');

console.log(todoList.get(0)); // 输出 Do laundry
console.log(todoList.get(1)); // 输出 Buy groceries

泛型提供了一种强大的方式可根据需要动态指定代码的类型参数,使代码更具灵活性和可重用性。