[TypeScript] Generic Functions, class, Type Inference and Generics
2024-10-01 12:32:28
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.
最新文章
- jQuery的加法运算.
- c++面试题目解析
- ASCIL码和字符的转换
- json 输出中文乱码解决办法
- Struts2 Action与Servlet API耦合
- Android 框架简介--Java环境(转)
- QPS、PV和需要部署机器数量计算公式(转)
- CRC 模式及实现
- Spring+SpringMVC+MyBatis+easyUI整合进阶篇(二)RESTful API实战笔记(接口设计及Java后端实现)
- servlet+jsp+jdbc实现从数据库查询用户信息到页面
- Vue+SpringBoot+Mybatis的简单员工管理项目
- CentOS7+CDH5.14.0安装全流程记录,图文详解全程实测-总目录
- 使用js下载文件
- C#基础---浅谈XML读取以及简单的ORM实现
- 面试题思考:GET和POST两种基本请求方法的区别
- python的初始化运行了哪些?
- [右键]如何添加Sublime为右键菜单
- MapperScannerConfigurer
- 【转】【Mysql】MySQL添加用户、删除用户与授权
- django基于cors做跨域处理
热门文章
- HDU 4354
- UVA 12124 UVAlive 3971 Assemble(二分 + 贪心)
- 兔子-RadioButton和RadioGroup的关系
- CodeForces 7D	 Palindrome Degree 字符串hash
- fgets()函数和sscanf()函数的使用方法
- linux虚拟机网络设置(本机使用wiff,自己的网)
- [Phonegap+Sencha Touch] 移动开发19 某些安卓手机上弹出消息框 点击后不消失的解决的方法
- PECL轻松安装PHP扩展
- CDH使用秘籍(一):Cloudera Manager和Managed Service的数据库
- 道里云SDN云网络技术:使云能够“众筹”