泛型的类型约束
https://coding.imooc.com/class/482.html
https://github.com/pengyw97/react17-ts4-hook-Jira
https://github.com/wt-maker/jira
<>里面写什么都可以,约定写 T<T>,什么类型不知道,- 像是一个占位符,或是一个类型变量;使用时,把定义好的变量当参数传入
- 使用时,动态传入类型值;灵活的约束参数的类型
T代表 Type,在定义泛型时通常用作第一个类型变量名称。实际上T可以用任何有效名称代替。除了T之外,可以随意起名常见泛型变量代表的意思:
- K(Key):表示对象中的键类型;
- V(Value):表示对象中的值类型;
- E(Element):表示元素类型
- U:在字母表中处于 T 下一位
function echo<T>(arg: T): T {return arg}const str: string = 'str'const result = echo(str)
�
function swap<T, U> (tuple: [T, U]): [U, T] {return [tuple[1], tuple[0]]}const result = swap(['string', 200])result[1]
�数组泛型
function echoLength<T>(arg: T): T {console.log(arg.length) // 报错,可能是数字,undefined或布尔值return arg}// 数组泛型function echoLength<T>(arg: T[]): T[] {console.log(arg.length)return arg}echoArray([10, 20])
