patryk-developer
5/18/2018 - 9:29 AM

Typy ogólne

< T > typ ogólny

//  typy ogólne
//  ========

class Concatenator< T > {
  concatenateArray(inputArray: Array< T >): string {
    let returnString = "";

    for (let i = 0; i < inputArray.length; i++) {
      if (i > 0)
        returnString += ",";
      returnString += inputArray[i].toString();
    }
    return returnString;
  }
}

var stringConcat = new Concatenator<string>();
var numberConcat = new Concatenator<number>();

let concatResult = stringConcat.concatenateArray(
  ["pierwszy", "drugi", "trzeci"]);
console.log(concatResult);

var stringArray: string[] = ["pierwszy", "drugi", "trzeci"];
var numberArray: number[] = [1, 2, 3];
var stringResult = 
  stringConcat.concatenateArray(stringArray);
var numberResult = 
  numberConcat.concatenateArray(numberArray);
// var stringResult2 = 
//     stringConcat.concatenateArray(numberArray);
// var numberResult2 = 
//     numberConcat.concatenateArray(stringArray);

class MyClass {
  private _name: string;
  constructor(arg1: number) {
    this._name = arg1 + "_MyClass";
  }
  toString(): string {
    return this._name;
  }
}

let myArray: MyClass[] = [
  new MyClass(1), 
  new MyClass(2), 
  new MyClass(3)];
  
let myArrayConcatentator = new Concatenator<MyClass>();
let myArrayResult = 
  myArrayConcatentator.concatenateArray(myArray);
console.log(myArrayResult);


//  ograniczanie typu T
//  ==========================

enum ClubHomeCountry {
  England,
  Germany
}

interface IFootballClub {
  getName() : string;
  getHomeCountry(): ClubHomeCountry;
}

abstract class FootballClub implements IFootballClub {
  protected _name: string;
  protected _homeCountry: ClubHomeCountry;
  getName() { return this._name };
  getHomeCountry() { return this._homeCountry };
}

class Liverpool extends FootballClub {
  constructor() {
    super();
    this._name = "Liverpool F.C.";
    this._homeCountry = ClubHomeCountry.England;
  }
}

class BorussiaDortmund extends FootballClub {
  constructor() {
    super();
    this._name = "Borussia Dortmund";
    this._homeCountry = ClubHomeCountry.Germany;
  }
}

class FootballClubPrinter< T extends IFootballClub  >
  implements IFootballClubPrinter< T > {
  print(arg : T) {
    console.log(` ${arg.getName()}` +
      `${this.IsEnglishTeam(arg)}` +
      `jest drużyną angielską.`
    );
  }
  IsEnglishTeam(arg : T) : string {
    if ( arg.getHomeCountry() == ClubHomeCountry.England ) 
      return "";
    else
      return "NIE "
  }
}

let clubInfo = new FootballClubPrinter();
clubInfo.print(new Liverpool());
clubInfo.print(new BorussiaDortmund());

interface IFootballClubPrinter < T extends IFootballClub > {
  print(arg : T);
  IsEnglishTeam(arg : T);
}