泛型的类型约束
https://coding.imooc.com/class/482.html
https://github.com/pengyw97/react17-ts4-hook-Jira
https://github.com/wt-maker/jira

  1. <> 里面写什么都可以,约定写 T <T>,什么类型不知道,
    1. 像是一个占位符,或是一个类型变量;使用时,把定义好的变量当参数传入
    2. 使用时,动态传入类型值;灵活的约束参数的类型
  2. T 代表 Type,在定义泛型时通常用作第一个类型变量名称。实际上 T 可以用任何有效名称代替。除了 T 之外,可以随意起名

  3. 常见泛型变量代表的意思:

    • K(Key):表示对象中的键类型;
    • V(Value):表示对象中的值类型;
    • E(Element):表示元素类型
    • U:在字母表中处于 T 下一位
  1. function echo<T>(arg: T): T {
  2. return arg
  3. }
  4. const str: string = 'str'
  5. const result = echo(str)

Generics泛型 - 图1

  1. function swap<T, U> (tuple: [T, U]): [U, T] {
  2. return [tuple[1], tuple[0]]
  3. }
  4. const result = swap(['string', 200])
  5. result[1]

�数组泛型

  1. function echoLength<T>(arg: T): T {
  2. console.log(arg.length) // 报错,可能是数字,undefined或布尔值
  3. return arg
  4. }
  5. // 数组泛型
  6. function echoLength<T>(arg: T[]): T[] {
  7. console.log(arg.length)
  8. return arg
  9. }
  10. echoArray([10, 20])