1. 泛型函数示例:
-
- function reverse<T>(arr: T[]): T[] {
- return arr.reverse();
- }
- const numbers = [1, 2, 3, 4, 5];
- const reversedNumbers = reverse<number>(numbers); // [5, 4, 3, 2, 1]
- const strings = ["apple", "banana", "orange"];
- const reversedStrings = reverse<string>(strings); // ["orange", "banana", "apple"]
2. 泛型接口示例:
-
- interface Pair<T, U> {
- first: T;
- second: U;
- }
- const pair: Pair<number, string> = { first: 1, second: "apple" };
- console.log(pair.first); // 1
- console.log(pair.second); // "apple"
3. 泛型类示例:1111111111111111111111111
-
- class Queue
{ - private elements: T[] = [];
- enqueue(element: T): void {
- this.elements.push(element);
- }
- dequeue(): T | undefined {
- return this.elements.shift();
- }
- }
- const queue = new Queue
(); - queue.enqueue(1);
- queue.enqueue(2);
- console.log(queue.dequeue()); // 1
- console.log(queue.dequeue()); // 2
4. 泛型约束示例:
-
- interface Shape {
- readonly x: number;
- readonly y: number;
- }
- function printShape<T extends Shape>(shape: T): void {
- console.log(`Shape at (${shape.x}, ${shape.y})`);
- }
- const rectangle = { x: 10, y: 20, width: 30, height: 40 };
- printShape(rectangle); // Shape at (10, 20)
5. 泛型函数类型示例:
-
- type MathOperation<T> = (a: T, b: T) => T;
- const add: MathOperation<number> = (a, b) => a + b;
- console.log(add(3, 4)); // 7
- const concat: MathOperation<string> = (a, b) => a + b;
- console.log(concat("hello", "world")); // "helloworld"