1. 泛型定义
泛型(Generics)指在定义函数、接口、类的时候,不预先指定具体的类型,而在使用的时候再指定类型的一种特性。
2.应用实例
function createArray(length: number, value: any): Array<any> {
let result = [];
for (let i = 0; i < length; ++i) {
result[i] = value;
}
return result;
}
//result: ['x','x','x']
console.log('array: ', createArray(3, 'x'));
function arrayGen<T>(length: number, value: T): Array<T> {
let result = [];
for (let i = 0; i < length; ++i) {
result[i] = value;
}
return result;
}
//result: ['x','x','x']
console.log('array: ', arrayGen<string>(3, 'x'));
function swap<T, U>(tuple: [T, U]): [U, T] {
return [tuple[1], tuple[0]]
}
//result['six',6]
swap([6, 'six']);
3.泛型约束
interface LengthWise {
length: number;
}
function loggingIdentity<T extends LengthWise>(arg: T): T {
console.log('length:', arg.length);
return arg;
}
// - error TS2345: Argument of type 'number' is not assignable to parameter of type 'LengthWise'.
loggingIdentity(7);
loggingIdentity("a");
function copyField<T extends U, U>(target: T, source: U): T {
for (let id in source) {
target[id] = (<T>source)[id]
}
return target;
}
let x = { a: 1, b: 2, c: 3, d: 4 }
copyField(x, { b: 10, d: 32 })
4.泛型接口
interface SearchFun {
(source: string, substring: string): boolean;
}
let mySearch: SearchFun;
mySearch = function (source: string, substring: string) {
return source.search(substring) !== -1;
}
interface ArrayGenFunc {
<T>(length: number, value: T): Array<T>;
}
let newArray: ArrayGenFunc;
newArray = function <T>(length: number, value: T): Array<T> {
let result: T[] = [];
for (let i = 0; i < length; ++i) {
result[i] = value;
}
return result;
}
newArray(3, 'x');
interface ArrayGenFuncG<T>{
(length:number , value:T):Array<T>;
}
let a: ArrayGenFuncG<any> ;
a = function<T>(length:number, value:T):Array<T>{
let result:T[] = [] ;
for(let i = 0 ; i < length ; ++i){
result[i] =value ;
}
return result ;
}
a(3 , 'x');
5.泛型类
class GenericNumber<T>{
zeroValue: T;
add: (x: T, y: T) => T;
}
let myGen = new GenericNumber<number>();
myGen.zeroValue = 0;
console.log('add:' + myGen.add(1, 2));
6.泛型参数默认类型
function createArr<T = string>(length: number, value: T): Array<T> {
let result: T[] = [];
for (let i = 0; i < length; ++i) {
result[i] = value;
}
return result;
}
console.log(createArr(2, 'x'));