1. function hello<T>(arg: T): T {
  2. return arg;
  3. }
  4. const output = hello<string>("hello world");
  5. const output = hello<string>(10); // 错误的 已经指定泛型是固定的string类型

通过来指定函数是一个泛型(当然字母可以随意也可以是ABCD等,通常是使用T),参数 T 也是泛型, 返回值也是泛型。泛型一开始是不指定确定的类型,只有在使用的时候才指定是固定的类型。
在使用的时候指定函数是一个字符串类型或者其他类型。

泛型应用

  1. function hello<T> (num: T): T {
  2. console.log(num.length); // 错误的 num是没有类型的,也就没有length属性
  3. return num;
  4. }

这样的情况下我们有些时候写代码就被限制死了,是不行的。

  1. function hello<T> (num: T[]): T[] {
  2. console.log(num.length); // 可以的,num的类型是被指定了数组, 数组是由length属性的
  3. return num;
  4. }
  5. const list:Array<string> = hello<String>(["1","2","3"]);

泛型类型

  1. function hello<T>(arg: T): T {
  2. return arg;
  3. }
  4. const myHello:<K>(arg: K) => K = hello; // 拉姆达表达式
  5. // const myHello:{<T>(arg: T): T} = hello; 这个等同于拉姆达表达式 结果是一样的
  6. myHello("hello"); // 这样就能指定函数泛型
  1. interface Hello {
  2. <T>(arg: T): T;
  3. }
  4. function myHello<T> (arg: T): T {
  5. return arg;
  6. }
  7. const mh:Hello = myHello;
  8. console.log(mh<string>("hello")); // 指定泛型 但是这样很不方便
  9. /*-------------------------------------------------------------*/
  10. interface Hello<T> {
  11. (arg: T): T;
  12. }
  13. function myHello<T> (arg: T): T {
  14. return arg;
  15. }
  16. const mh:Hello<number> = myHello; // 这样指定泛型更加简单
  17. console.log(mh(100));

泛型类

  1. class HelloNumber<T> {
  2. ten: T;
  3. add(x: T, Y: T) => T;
  4. }
  5. const myHello = new HelloNumber<number>(); // 不一定是number 可以是其他数据类型
  6. myHello.ten = 10;
  7. myHello.add = function(x, y){
  8. return x + y;
  9. }
  10. console.log(myHello.ten); // 10;
  11. console.log(myHello.add(1, 2)); // 3