Generic Fucntion:

For example we have a set of data and an function:

interface HasName {
name: string;
} const heros: HasName[] = [
{name: 'Jno'},
{name: 'Miw'},
{name: 'Ggr'},
{name: 'Gew'},
{name: 'Wfe'}
]; function cloneArray(ary: any[]): any[] {
return ary.slice();
} const clones = cloneArray(heros);

When we check the 'clones' type, you can see it is 'any[]'.

To add more type information we can change the function:

function cloneArray<T>(ary: T[]): T[] {
return ary.slice();
}

Now we get 'clones' type as 'HasName[]'.

Generic Class:

class SuperCharacter {
constructor(public name: string) { }
} class Hero extends SuperCharacter { } class SuperTeam {
constructor(public members: SuperCharacter[],
public leader: SuperCharacter
) { }
} const captainAmerica = new Hero('Captain America');
const thor = new Hero('Thor');
const ironMan = new Hero('IronMan'); const avengers = new SuperTeam(
[captainAmerica, thor, ironMan],
captainAmerica
); const members = avengers.members;

If we check 'avengers' type is 'SuperTeam'. 'memebers' type is 'SuperCharacter[]'.

To add more information to the types we can do:

class SuperTeam<T> {
constructor(public members: T[],
public leader: T
) { }
}

Now the 'avengers' type is 'SuperTeam<Hero>' and 'members' type is 'Hero[]'.

Now, let's say we have another class:

class Villain extends SuperCharacter {

}

Have some members.

const luthor = new Villain('Luthor');
const bizarro = new Villain('Bizarro');
const captainCold = new Villain('Captain Cold'); const megaCrossoverTeam = new SuperTeam([
captainAmerica, thor, ironMan, luthor,
bizarro, captainCold
], captainAmerica);

'megaCrossoverTeam' is type of 'SuperTeam<Hero | Villain>'.

If we want to add some restrictions to the class, we can do:

class SuperTeam<T extends SuperCharacter> {
constructor(public members: T[],
public leader: T
) { }
}

Then the example below will throw error:

const avengers = new SuperTeam(
[, , ], );

Because the type is number.

最新文章

  1. jQuery的加法运算.
  2. c++面试题目解析
  3. ASCIL码和字符的转换
  4. json 输出中文乱码解决办法
  5. Struts2 Action与Servlet API耦合
  6. Android 框架简介--Java环境(转)
  7. QPS、PV和需要部署机器数量计算公式(转)
  8. CRC 模式及实现
  9. Spring+SpringMVC+MyBatis+easyUI整合进阶篇(二)RESTful API实战笔记(接口设计及Java后端实现)
  10. servlet+jsp+jdbc实现从数据库查询用户信息到页面
  11. Vue+SpringBoot+Mybatis的简单员工管理项目
  12. CentOS7+CDH5.14.0安装全流程记录,图文详解全程实测-总目录
  13. 使用js下载文件
  14. C#基础---浅谈XML读取以及简单的ORM实现
  15. 面试题思考:GET和POST两种基本请求方法的区别
  16. python的初始化运行了哪些?
  17. [右键]如何添加Sublime为右键菜单
  18. MapperScannerConfigurer
  19. 【转】【Mysql】MySQL添加用户、删除用户与授权
  20. django基于cors做跨域处理

热门文章

  1. HDU 4354
  2. UVA 12124 UVAlive 3971 Assemble(二分 + 贪心)
  3. 兔子-RadioButton和RadioGroup的关系
  4. CodeForces 7D Palindrome Degree 字符串hash
  5. fgets()函数和sscanf()函数的使用方法
  6. linux虚拟机网络设置(本机使用wiff,自己的网)
  7. [Phonegap+Sencha Touch] 移动开发19 某些安卓手机上弹出消息框 点击后不消失的解决的方法
  8. PECL轻松安装PHP扩展
  9. CDH使用秘籍(一):Cloudera Manager和Managed Service的数据库
  10. 道里云SDN云网络技术:使云能够“众筹”