• ts 泛型基础介绍


    泛型:指的是,在定义函数/接口/类型...时,不预先指定具体的类型,而是在使用的时候再指定类型限制的一种特性


    当我们定义一个变量,但不确定其类型的时候,有两种解决方式:

    1. 方式1:使用any
      使用any定义时存在的问题:虽然已知道传入值的类型,但是无法获取函数返回值的类型;另外也失去了ts类型保护的优势。
    2. 方式2:使用泛型
      泛型:在定义函数/接口/类型...时,不预先指定具体的类型,而是在使用的时候再指定类型限制的一种特性。

    1. 在函数中使用泛型
      使用方式:类似于函数传参,传什么数据类型,T就表示什么数据类型,使用时T也可以换成任意字符串
    function test<T>(arg: T): T {
      console.log('泛型=', arg)
      return arg
    }
    test<number>(123456) // 返回值是number类型的123456
    test<string | boolean>('hahahaha') // 返回值是string类型的hahahaha
    test<string | boolean>(false)
    
    const test1 = <T>(arg: T): T => {
      console.log('泛型=', arg)
      return arg
    }
    const ret1 = test1<string>('Hello')
    const ret2 = test1<number>(42)
    const ret3 = test<number[]>([1, 2, 3])
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    1. 在接口中使用泛型
    interface Search {
      <T, Y>(name: T, age: Y): T // 注意:这里写法是定义的方法哦。。。。。。
    }
    
    let fn: Search = function <T, Y>(name: T, id: Y): T {
      console.log(name, id)
      return name
    }
    fn('li', 11) // 编译器会自动识别传入的参数,将传入的参数的类型认为是泛型指定的类型
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9

    1. 使用接口约束泛型
    interface Person {
     zname: string
     zage: number
    }
    function student<T extends Person>(arg: T): T {
     return arg
    }
    // 例子1:传入满足 Person 接口的对象
    const person: Person = { zname: 'Alice', zage: 25 }
    const result1 = student(person) // 返回类型为 Person
    
    // 例子2:传入满足 Person 接口的子类型的对象
    class Student implements Person {
     zname: string
     zage: number
     constructor(name: string, age: number) {
       this.zname = name
       this.zage = age
     }
    }
    const studentObj = new Student('Bob', 30)
    const result2 = student(studentObj) // 返回类型为 Student
    
    // 例子3:传入不满足 Person 接口的对象
    const invalidObj = { zname: 'Charlie', zage: '20' } // 注意:zage 的类型错误
    // const result3 = student(invalidObj); // 报错:类型 "{ zname: string; zage: string; }" 的参数不能赋给类型 "Person" 的参数
    
    // 例子4:传入不满足 Person 接口的对象,但使用类型断言绕过类型检查
    // const invalidObj2 = { zname: 'Charlie', zage: '20' } as Person; // 使用类型断言
    // const result4 = student(invalidObj2); // 返回类型为 Person
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
  • 相关阅读:
    JDK 和 JRE 、final 与 static 、堆和栈
    screen对象
    校园网升级改造怎么做
    Selenium WebDriver类的常用属性和方法汇总
    hot100-课程表
    在Ubuntu系统安装Anaconda及Python
    PyTorch入门学习(十六):网络模型的保存与读取
    HTML+CSS简单漫画网页设计成品 蜡笔小新3页 大学生个人HTML网页制作作品
    配置云服务器(Ubuntu)的vnc守护进程(服务)
    Qt蓝牙:搜索蓝牙设备的类——QBluetoothDeviceDiscoveryAgent
  • 原文地址:https://blog.csdn.net/pig_ning/article/details/132906920