1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144
| function fnn(x:number,y:number):number[]{ return [x,y] }
function fnn(x:string,y:string):string[]{ return [x,y] }
function fnn(x:boolean,y:boolean):boolean[]{ return [x,y] }
因此我们可以将类型用一个变量替代,在使用的时候,将变量类型传过去。
①、泛型变量 泛型变量 T ,T 表示任何类型,也可以用其他字母代替 因此我们上面的代码可以写成:
function declaration<T>(x: T, y: T): T[] { return [x, y]; }
const expression = <T>(n1: T, n2: T): T[] => { return [n1, n2]; }; console.log(declaration<string>("1", "2")); console.log(expression<boolean>(true, false)); console.log(expression<number>(6, 7));
console.log(expression<number | string>(6, "a")); console.log(expression(1, 23));
let limit1 = <T>(str: string | T[]): number => { return str.length; }; console.log(limit1<number>([1, 3]));
let limit2 = <T extends String>(arr: T): number => { return arr.length; }; console.log(limit2<string>("one")); //3
//泛型的接口约束:就是让这个变量必须有length属性,此时就限定了变量类型有length属性,只能为string ,或者数组类型 interface ILengthNum { length: number; } const limit3 = <T extends ILengthNum>(str: T): number => { return str.length; }; console.log(limit3<string>("oneworld")); //8 console.log(limit3<string[]>(["dasjd", "dhksah", "dahskdha"])); //3 console.log(limit3<number[]>([12, 456, 79, 465])); //4
//多个类型参数 const multi = <N, S>(sum: [N, S]): [S, N] => { return [sum[1], sum[0]]; //实现的是交换数组内两项的位置 }; console.log(multi<number, string>([1, "one"])); //["one",1]
②泛型接口
//泛型接口 interface genface1 { <T>(a: T, b: T): boolean; } const func1: genface1 = (x, y) => { return x == y; }; console.log(func1<number>(1111, 5)); //false console.log(func1<string>("abc", "abc")); //true
//另一种 把泛型参数提前放在接口名上 interface genface2<T> { (a: T, b: T): boolean; } const func2: genface2<number> = (x, y) => { return x == y; }; console.log(func2(7, 5)); //false
//另一种写法,先定义类型,再赋值函数 let func3: genface2<string>; func3 = (x, y) => { return x == y; }; console.log(func3("abc", "abc")); //true
//多类型泛型接口 interface createA3<N, T> { (a: N, b: T): Array<T>; } let func4: createA3<number, string>; func4 = function (i, s) { let arr: string[] = []; arr[i] = s; return arr; }; func4(1, "dqwy");
//泛型约束 interface Length4 { length: number; } interface createA4<N, T extends Length4> { (a: N, b: T): string; } let func5: createA4<number, string>; func5 = function (i, s) { //var arr:string[] = [] //return arr return s; }; func5(2, "dqwy");
③用泛型变量和any的区别
//使用泛型变量 T function fun6<T>(x: T, y: T): T[] { return [x, y]; } fun6<string>("a", "b");
//使用 any:缺点就是传入的类型和返回的类型不确定 function fun7(x: any, y: any): any[] { return [x, y]; } fun7("a", "b");
|