在TypeScript中,泛型是一种强大的工具,可以让我们在编写代码时更加灵活和可复用。下面是一些泛型的常见用法示例:

1. 泛型约束

function printLength<T extends { length: number }>(arg: T): void {
  console.log(arg.length);
}

printLength("Hello");  // 输出:5
printLength([1, 2, 3]);  // 输出:3
printLength({ length: 10 });  // 输出:10
printLength(123);  // 编译错误:类型“123”的参数不能赋给类型“T”,因为类型“123”缺少类型“length”

2. 泛型类

class Stack<T> {
  private items: T[] = [];

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

  pop(): T | undefined {
    return this.items.pop();
  }
}

const numberStack = new Stack<number>();
numberStack.push(1);
numberStack.push(2);
console.log(numberStack.pop());  // 输出:2

const stringStack = new Stack<string>();
stringStack.push("Hello");
stringStack.push("World");
console.log(stringStack.pop());  // 输出:World

3. 泛型函数

function reverseArray<T>(array: T[]): T[] {
  return array.reverse();
}

console.log(reverseArray([1, 2, 3]));  // 输出:[3, 2, 1]
console.log(reverseArray(["Hello", "World"]));  // 输出:["World", "Hello"]

4. 泛型接口

interface Pair<T, U> {
  first: T;
  second: U;
}

const pair: Pair<string, number> = {
  first: "Hello",
  second: 123
};

这些只是泛型的一部分应用场景,TypeScript的泛型功能非常丰富,可以帮助开发者编写更加强大和灵活的代码。