源码

  • ts ``` //声明一个泛型类型的函数 function Hello(arg:T):T { return arg; } //声明一个方法该方法引用上面的泛型类型的函数 let myHello:(arg:T) => T = Hello; alert(myHello(‘xiaochuan’));
  1. - HTML

<!DOCTYPE html>

  1. - 浏览器效果图
  2. > ![image.png](http://upload-images.jianshu.io/upload_images/9064013-b4f01944b1b88ee5.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)<br />
  3. ####扩展
  4. - Lam.ts

//简单的解释 => 表达式 //myFunc 函数名称 + 参数类型 + 返回值类型 //后面是定义这个函数的内容 参数必须是 number 类型 返回值也必须是 string 类型 // let myFunc:(a:number) => string = function(a:number):string{ // return ‘hello’ + a; // } //实际上在后面定义函数实际内容的时候其本身就有 函数检查 所以其实可以将这个函数写成如下所示的样子 let myFunc = function(a:number):string{ return ‘hello’ + a; } alert(myFunc(2));

  1. - HTML

<!DOCTYPE html>

  1. - 浏览器效果图
  2. > ![image.png](http://upload-images.jianshu.io/upload_images/9064013-245d70ed819a67b3.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)<br />
  3. ####使用另一种方法实现示例一的功能
  4. - ts

// //声明一个泛型类型的函数 function Hello(arg:T):T { return arg; } // //声明一个方法该方法引用上面的泛型类型的函数 // let myHello:(arg:T) => T = Hello; // alert(myHello(‘xiaochuan’));

//使用另一种写法实现上面的定义 let myHello:{(arg:T):T} = Hello; alert(myHello(‘xiaochuan’));

  1. - HTML

<!DOCTYPE html>

  1. - 浏览器效果图
  2. > ![image.png](http://upload-images.jianshu.io/upload_images/9064013-e8a07f52058e04dc.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)<br />
  3. ####下面是在接口中泛型的使用
  4. - ts

//下面是在接口中对泛型的使用 //定义一个有一个泛型函数的接口 interface Hello{ //定义一个泛型的函数 (arg:T):T; } //声明一个泛型函数 function myHello(arg:T):T{ return arg; } //声明一个引用 Hello 接口类型的函数 函数的值引用 myHello 函数 let MH:Hello = myHello; // alert(MH(‘xiaochuan’));//这样并没有用到泛型 //下面是使用泛型的好处的实现 alert(MH(‘xiaochuan’));

  1. - HTML 与上例一致
  2. - 浏览器效果图
  3. > ![image.png](http://upload-images.jianshu.io/upload_images/9064013-6ad68c0f94347c60.png?imageMogr2/auto-orient/strip%7CimageView2/2/w/1240)<br />
  4. ####下面是在接口中对泛型使用的另一种写法
  5. - ts

//下面是在接口中对泛型使用的另一种写法 //在接口定义的时候就指定其为泛型 interface Hello{ (arg:T):T; } //声明一个泛型函数 function myHello(arg:T):T{ return arg; } //声明一个引用自接口且为 number 类型的函数 let mh:Hello = myHello; //这样的话这个参数就只能是 number 类型 alert(mh(29));

```

  • HTML 与上例相同
  • 浏览器效果图

image.png