基本使用
传入类型不确定,希望传入和传出类型相同
泛型是一个类型变量
定义function identity<T>(x:T):T{return ...}执行identity<number>(123);变量let a:number[] = [1,2,3];let a:Array<number> = [1,2,3];接口interface MyArray<T>{[n:number]:T;}
泛型类型
函数泛型注解
let fn:<T>(arg:T)=>T = function(){}
对象字面量的方式来定义泛型类型
let a:{<T>(arg:T):T}=identity;或者interface IdentityInterface{<T>(arg:T):T;}let a:IdentityInterface = identity;使用的使用再判断a(123);或者interface IdentityInterface<T>{(arg:T):T;}let a:IdentityInterface<number> = identity;
泛型类
基本例子
class G<T>{value:T;add:(x:T,y:T)=>T;}let a = new G<number>();a.value = 50;a.add = function(1,2){return x+y;}
泛型约束
通过泛型继承接口实现,保证某种泛型上有某种方法
interface saveGeneric{width:number;length:(x:number,y:number)=>number;}function hello<T extends saveGeneric>(x:T){let a = x.width,b = x.length(1,2);return a+b}
在泛型约束中使用类型参数
keyof
拿所有的键名当字符串类型
interface Person{name:string;age:number;}type P1 = keyof Person;为键名的联合类型,包括name,age的字符串type P2 = keyof Person[];为所有键名的联合类型,包括name,age,splice,caocant,push...的字符串
多重泛型约束
举例1
function extend<T,U>(f:T,s:U):T&U{let result = <T&U>{};for(let x in f){(<any>result)[x] = (<any>f)[x]}for(let x in s){(<any>result)[x] = (<any>f)[x]}return result;}class Person{constructor(public name:string){}}class Console{log(){}}let jim = extend(new Person('node.js'),new Console());console.log(jim.name);jim.log();
举例2
interface Sentence{length:number;}interface Music{name:string;}class Test<T extends Sentence & Music>{props:Tconstructor(arg:T){this.props = arg;}info(){return{name:this.props.name,lenght:this.props.length}}}
交叉类型与联合类型
intersetion types:&
同时有两类型的特点
union types:|
为其中一个类型
断言:
let a = <T&U>{};let a = {} as T&U;
泛型里使用类类型
class BeeKeeper{nametag:string;}class ZooKeeper{hashMap:boolean;}class Animal{legs:number;}class Bee{keeper:BeeKeeper;}class Lion{keeper:ZooKeeper;}function createInstance<A extends Animal>(c:new()=>A):A{return new c();}create Instance(Bee).keeper.nametag;create Instance(Lion).keeper.hashmap;
