基本使用

传入类型不确定,希望传入和传出类型相同
泛型是一个类型变量

  1. 定义
  2. function identity<T>(x:T):T{
  3. return ...
  4. }
  5. 执行
  6. identity<number>(123);
  7. 变量
  8. let a:number[] = [1,2,3];
  9. let a:Array<number> = [1,2,3];
  10. 接口
  11. interface MyArray<T>{
  12. [n:number]:T;
  13. }

泛型类型

函数泛型注解

  1. let fn:<T>(arg:T)=>T = function(){}

对象字面量的方式来定义泛型类型

  1. let a:{<T>(arg:T):T}=identity;
  2. 或者
  3. interface IdentityInterface{
  4. <T>(arg:T):T;
  5. }
  6. let a:IdentityInterface = identity;
  7. 使用的使用再判断
  8. a(123);
  9. 或者
  10. interface IdentityInterface<T>{
  11. (arg:T):T;
  12. }
  13. let a:IdentityInterface<number> = identity;

泛型类

Generic

基本例子

  1. class G<T>{
  2. value:T;
  3. add:(x:T,y:T)=>T;
  4. }
  5. let a = new G<number>();
  6. a.value = 50;
  7. a.add = function(1,2){
  8. return x+y;
  9. }

泛型约束

通过泛型继承接口实现,保证某种泛型上有某种方法

  1. interface saveGeneric{
  2. width:number;
  3. length:(x:number,y:number)=>number;
  4. }
  5. function hello<T extends saveGeneric>(x:T){
  6. let a = x.width,
  7. b = x.length(1,2);
  8. return a+b
  9. }

在泛型约束中使用类型参数

keyof
拿所有的键名当字符串类型

  1. interface Person{
  2. name:string;
  3. age:number;
  4. }
  5. type P1 = keyof Person;
  6. 为键名的联合类型,包括name,age的字符串
  7. type P2 = keyof Person[];
  8. 为所有键名的联合类型,包括name,agesplice,caocant,push...的字符串

多重泛型约束

举例1

  1. function extend<T,U>(f:T,s:U):T&U{
  2. let result = <T&U>{};
  3. for(let x in f){
  4. (<any>result)[x] = (<any>f)[x]
  5. }
  6. for(let x in s){
  7. (<any>result)[x] = (<any>f)[x]
  8. }
  9. return result;
  10. }
  11. class Person{
  12. constructor(public name:string){}
  13. }
  14. class Console{
  15. log(){}
  16. }
  17. let jim = extend(new Person('node.js'),new Console());
  18. console.log(jim.name);
  19. jim.log();

举例2

  1. interface Sentence{
  2. length:number;
  3. }
  4. interface Music{
  5. name:string;
  6. }
  7. class Test<T extends Sentence & Music>{
  8. props:T
  9. constructor(arg:T){
  10. this.props = arg;
  11. }
  12. info(){
  13. return{
  14. name:this.props.name,
  15. lenght:this.props.length
  16. }
  17. }
  18. }

交叉类型与联合类型

intersetion types:&
同时有两类型的特点
union types:|
为其中一个类型
断言:

  1. let a = <T&U>{};
  2. let a = {} as T&U;

泛型里使用类类型

  1. class BeeKeeper{
  2. nametag:string;
  3. }
  4. class ZooKeeper{
  5. hashMap:boolean;
  6. }
  7. class Animal{
  8. legs:number;
  9. }
  10. class Bee{
  11. keeper:BeeKeeper;
  12. }
  13. class Lion{
  14. keeper:ZooKeeper;
  15. }
  16. function createInstance<A extends Animal>(c:new()=>A):A{
  17. return new c();
  18. }
  19. create Instance(Bee).keeper.nametag;
  20. create Instance(Lion).keeper.hashmap;