泛型函数
看示例好像是规定了传入参数和传出参数一致
function getName<T>(name:T):T {
return name;
}
console.log(getName(123));
那传入数组,返回number,能否这样写:
function getName<T>(name:Array<T>):T {
return name.length;
}
console.log(getName([1,2,3]));
error TS2322: Type 'number' is not assignable to type 'T'.
'number' is assignable to the constraint of type 'T', but 'T' could be instantiated with a different subtype of constraint '{}'.
能想到的就是将:T改成:number。
我们先接着看泛型类型
回顾一下函数接口
function identity<T>(arg: T): T {
return arg;
}
//let myIdentity: <T>(arg: T) => T = identity;
let myIdentity: (arg: number) =>number ;
myIdentity=identity;
console.log(myIdentity(123));
现在注释部分是不是就好理解了。
这个大括号我们在函数解构里见过,回顾一下:
函数声明可以修改为interface,
interface C{
a:string,
b?:number
}
function f({a,b}:C):void {
}
f({a:'1',b:1});
那么大括号和interface可以互换,我们把上面的对象字面量改成接口
function identity<T>(arg: T): T {
return arg;
}
let myIdentity: {<T>(arg: T): T} = identity;
identity(1);
改成
interface Identity{
(art:number):number
}
function identity<T>(arg: T): T {
return arg;
}
let myIdentity:Identity = identity;
console.log(identity(1));
现在我么指定的是number类型,再次将接口改成任意类型
interface Identity<T>{
(art:T):T
}
function identity<T>(arg: T): T {
return arg;
}
let myIdentity:Identity<number> = identity;
console.log(identity(1));
后面的<number>要是不指定,或模仿着指定<T>,会报错:
error TS2314: Generic type 'Identity<T>' requires 1 type argument(s).
9 let myIdentity:Identity = identity;
参考文档给的示例,原来是要把T放在接口里面,如下:
interface Identity{
<T>(art:T):T
}
function identity<T>(arg: T): T {
return arg;
}
let myIdentity:Identity= identity;
console.log(identity(1));
Indentity<T>这样写是指定了泛型的参数类型,如下:
接下来看泛型类:
我修改一下:
class GenericNumber<T,U> {
zeroValue: T;
add: (x: T, y: U) => T;
}
let myGenericNumber = new GenericNumber<number,string>();
myGenericNumber.zeroValue = 0;
myGenericNumber.add = function(x, y) { return x};
console.log(myGenericNumber.add(1,'a'));