• ts中的泛型


    1. 泛型函数示例:

    1. function reverse<T>(arr: T[]): T[] {
    2. return arr.reverse();
    3. }
    4. const numbers = [1, 2, 3, 4, 5];
    5. const reversedNumbers = reverse<number>(numbers); // [5, 4, 3, 2, 1]
    6. const strings = ["apple", "banana", "orange"];
    7. const reversedStrings = reverse<string>(strings); // ["orange", "banana", "apple"]

    2. 泛型接口示例:

    1. interface Pair<T, U> {
    2. first: T;
    3. second: U;
    4. }
    5. const pair: Pair<number, string> = { first: 1, second: "apple" };
    6. console.log(pair.first); // 1
    7. console.log(pair.second); // "apple"

    3. 泛型类示例:1111111111111111111111111

    1. class Queue {
    2. private elements: T[] = [];
    3. enqueue(element: T): void {
    4. this.elements.push(element);
    5. }
    6. dequeue(): T | undefined {
    7. return this.elements.shift();
    8. }
    9. }
    10. const queue = new Queue();
    11. queue.enqueue(1);
    12. queue.enqueue(2);
    13. console.log(queue.dequeue()); // 1
    14. console.log(queue.dequeue()); // 2

    4. 泛型约束示例:

    1. interface Shape {
    2. readonly x: number;
    3. readonly y: number;
    4. }
    5. function printShape<T extends Shape>(shape: T): void {
    6. console.log(`Shape at (${shape.x}, ${shape.y})`);
    7. }
    8. const rectangle = { x: 10, y: 20, width: 30, height: 40 };
    9. printShape(rectangle); // Shape at (10, 20)

    5. 泛型函数类型示例:

    1. type MathOperation<T> = (a: T, b: T) => T;
    2. const add: MathOperation<number> = (a, b) => a + b;
    3. console.log(add(3, 4)); // 7
    4. const concat: MathOperation<string> = (a, b) => a + b;
    5. console.log(concat("hello", "world")); // "helloworld"
  • 相关阅读:
    STC15单片机-生产资料,项目结束
    JAVA工具----maven(一)
    日常开发Git命令
    小程序 BUG 记录
    【input学习】App对input事件的反馈与waitqueue
    SpringBoot 自定义参数校验(5)
    义乌个体户
    Spring application.properties
    SpringBoot:ch03 yml 数据绑定示例
    semaphore in os
  • 原文地址:https://blog.csdn.net/m0_47999208/article/details/133298631