5. 泛型

指在定义函数、接口或类的时候,不预先指定具体的类型,而在使用的时候再指定具体类型的一种特性。

引入

下面创建一个函数, 实现功能: 根据指定的数量 count 和数据 value , 创建一个包含 count 个 value 的数组
不用泛型的话,这个函数可能是下面这样:

  1. function createArray(value: any, count: number): any[] {
  2. const arr: any[] = []
  3. for (let index = 0; index < count; index++) {
  4. arr.push(value)
  5. }
  6. return arr
  7. }
  8. const arr1 = createArray(11, 3)
  9. const arr2 = createArray('aa', 3)
  10. console.log(arr1[0].toFixed(), arr2[0].split(''))

使用函数泛型

  1. function createArray2 <T> (value: T, count: number) {
  2. const arr: Array<T> = []
  3. for (let index = 0; index < count; index++) {
  4. arr.push(value)
  5. }
  6. return arr
  7. }
  8. const arr3 = createArray2<number>(11, 3)
  9. console.log(arr3[0].toFixed())
  10. // console.log(arr3[0].split('')) // error
  11. const arr4 = createArray2<string>('aa', 3)
  12. console.log(arr4[0].split(''))
  13. // console.log(arr4[0].toFixed()) // error

多个泛型参数的函数

一个函数可以定义多个泛型参数

  1. function swap <K, V> (a: K, b: V): [K, V] {
  2. return [a, b]
  3. }
  4. const result = swap<string, number>('abc', 123)
  5. console.log(result[0].length, result[1].toFixed())

泛型接口

在定义接口时, 为接口中的属性或方法定义泛型类型
在使用接口时, 再指定具体的泛型类型

  1. interface IbaseCRUD <T> {
  2. data: T[]
  3. add: (t: T) => void
  4. getById: (id: number) => T
  5. }
  6. class User {
  7. id?: number; //id主键自增
  8. name: string; //姓名
  9. age: number; //年龄
  10. constructor (name, age) {
  11. this.name = name
  12. this.age = age
  13. }
  14. }
  15. class UserCRUD implements IbaseCRUD <User> {
  16. data: User[] = []
  17. add(user: User): void {
  18. user = {...user, id: Date.now()}
  19. this.data.push(user)
  20. console.log('保存user', user.id)
  21. }
  22. getById(id: number): User {
  23. return this.data.find(item => item.id===id)
  24. }
  25. }
  26. const userCRUD = new UserCRUD()
  27. userCRUD.add(new User('tom', 12))
  28. userCRUD.add(new User('tom2', 13))
  29. console.log(userCRUD.data)

泛型类

在定义类时, 为类中的属性或方法定义泛型类型
在创建类的实例时, 再指定特定的泛型类型

  1. class GenericNumber<T> {
  2. zeroValue: T
  3. add: (x: T, y: T) => T
  4. }
  5. let myGenericNumber = new GenericNumber<number>()
  6. myGenericNumber.zeroValue = 0
  7. myGenericNumber.add = function(x, y) {
  8. return x + y
  9. }
  10. let myGenericString = new GenericNumber<string>()
  11. myGenericString.zeroValue = 'abc'
  12. myGenericString.add = function(x, y) {
  13. return x + y
  14. }
  15. console.log(myGenericString.add(myGenericString.zeroValue, 'test'))
  16. console.log(myGenericNumber.add(myGenericNumber.zeroValue, 12))

泛型约束

如果我们直接对一个泛型参数取 length 属性, 会报错, 因为这个泛型根本就不知道它有这个属性

  1. // 没有泛型约束
  2. function fn <T>(x: T): void {
  3. // console.log(x.length) // error
  4. }

我们可以使用泛型约束来实现

  1. interface Lengthwise {
  2. length: number;
  3. }
  4. // 指定泛型约束
  5. function fn2 <T extends Lengthwise>(x: T): void {
  6. console.log(x.length)
  7. }

我们需要传入符合约束类型的值,必须包含必须 length 属性:

  1. fn2('abc')
  2. // fn2(123) // error number没有length属性