You signed in with another tab or window. Reload to refresh your session.You signed out in another tab or window. Reload to refresh your session.You switched accounts on another tab or window. Reload to refresh your session.Dismiss alert
// 泛型变量的使用
function identity<T>(arg:T):T{
console.log(typeof arg);
return arg;
}
let output1=identity<string>('myString');
let output2=identity('myString');
let output3:number=identity<number>(100);
let output4:number=identity(200);
// 使用集合的泛型
function loggingIdentity<T>(arg:Array<T>):Array<T>{
console.log(arg.length);
return arg;
}
loggingIdentity([1,2,3]);
2.定义泛型函数
// 泛型函数
function identity<T>(arg:T):T{
return arg;
}
let myIdentity:{<T>(arg:T):T}=identity;
3.定义泛型接口
// 泛型接口
interface GenericIdentityFn<T> {
(arg: T): T;
}
function identity<T>(arg: T): T {
return arg;
}
let myIdentity: GenericIdentityFn<number> = identity;
4.定义泛型类
// 泛型类
class GenericNumber<T>{
zeroValue:T;
add:(x:T,y:T)=>T;
}
let myGenericNumber=new GenericNumber<number>();
myGenericNumber.zeroValue=0;
myGenericNumber.add=function(x,y){return x+y;};
console.info(myGenericNumber.add(2,5));
let stringNumberic=new GenericNumber<string>();
stringNumberic.zeroValue='abc';
stringNumberic.add=function(x,y){return `${x}--${y}`};
console.info(stringNumberic.add('张三丰','诸葛亮'));
说一说Typescript中的泛型的作用及使用场景。
The text was updated successfully, but these errors were encountered: