onsa
2/11/2017 - 8:51 PM

Generics

Generics

//  declare wildcards for unknown types by adding them in <> after the class/interface name
class Tuple<T1, T2> {
  constructor(public item1: T1, public item2: T2) {             //  use those wildcards within the class
  }
}

interface Pair<T> {
  item1: T;
  item2: T;
}

//  in functions, declare wildcards after the keyword function; then use them in parameter definition
var pairToTuple = function<T>(p: Pair<T>) {
  return new Tuple(p.item1, p.item2);
};

var tuple = pairToTuple({ item1:"hello", item2:"world"});