1. 泛型定义

泛型(Generics)指在定义函数、接口、类的时候,不预先指定具体的类型,而在使用的时候再指定类型的一种特性。

2.应用实例

  1. function createArray(length: number, value: any): Array<any> {
  2. let result = [];
  3. for (let i = 0; i < length; ++i) {
  4. result[i] = value;
  5. }
  6. return result;
  7. }
  8. //result: ['x','x','x']
  9. console.log('array: ', createArray(3, 'x'));
  1. function arrayGen<T>(length: number, value: T): Array<T> {
  2. let result = [];
  3. for (let i = 0; i < length; ++i) {
  4. result[i] = value;
  5. }
  6. return result;
  7. }
  8. //result: ['x','x','x']
  9. console.log('array: ', arrayGen<string>(3, 'x'));
  1. function swap<T, U>(tuple: [T, U]): [U, T] {
  2. return [tuple[1], tuple[0]]
  3. }
  4. //result['six',6]
  5. swap([6, 'six']);

3.泛型约束

  1. interface LengthWise {
  2. length: number;
  3. }
  4. function loggingIdentity<T extends LengthWise>(arg: T): T {
  5. console.log('length:', arg.length);
  6. return arg;
  7. }
  8. // - error TS2345: Argument of type 'number' is not assignable to parameter of type 'LengthWise'.
  9. loggingIdentity(7);
  10. loggingIdentity("a");
  11. function copyField<T extends U, U>(target: T, source: U): T {
  12. for (let id in source) {
  13. target[id] = (<T>source)[id]
  14. }
  15. return target;
  16. }
  17. let x = { a: 1, b: 2, c: 3, d: 4 }
  18. copyField(x, { b: 10, d: 32 })

4.泛型接口

  1. interface SearchFun {
  2. (source: string, substring: string): boolean;
  3. }
  4. let mySearch: SearchFun;
  5. mySearch = function (source: string, substring: string) {
  6. return source.search(substring) !== -1;
  7. }
  8. interface ArrayGenFunc {
  9. <T>(length: number, value: T): Array<T>;
  10. }
  11. let newArray: ArrayGenFunc;
  12. newArray = function <T>(length: number, value: T): Array<T> {
  13. let result: T[] = [];
  14. for (let i = 0; i < length; ++i) {
  15. result[i] = value;
  16. }
  17. return result;
  18. }
  19. newArray(3, 'x');
  20. interface ArrayGenFuncG<T>{
  21. (length:number , value:T):Array<T>;
  22. }
  23. let a: ArrayGenFuncG<any> ;
  24. a = function<T>(length:number, value:T):Array<T>{
  25. let result:T[] = [] ;
  26. for(let i = 0 ; i < length ; ++i){
  27. result[i] =value ;
  28. }
  29. return result ;
  30. }
  31. a(3 , 'x');

5.泛型类

  1. class GenericNumber<T>{
  2. zeroValue: T;
  3. add: (x: T, y: T) => T;
  4. }
  5. let myGen = new GenericNumber<number>();
  6. myGen.zeroValue = 0;
  7. console.log('add:' + myGen.add(1, 2));

6.泛型参数默认类型

  1. function createArr<T = string>(length: number, value: T): Array<T> {
  2. let result: T[] = [];
  3. for (let i = 0; i < length; ++i) {
  4. result[i] = value;
  5. }
  6. return result;
  7. }
  8. console.log(createArr(2, 'x'));