Generic functions are defined by declaring a type parameter when declaring the function ,in angular brackets.The type parameter is the placeholder which is replaced by the actual type arguments when the program executes.
So we define a generic method as:
function GenericFunction<T>(items: T[]): T[] {
The placeholder T above is the type parameter which is replaced by the actual type when the program executes.
So actual value of T could be one of the different data types such number or string.
In the following example we are declaring a GenericFunction which has a type parameter T.Since it is a generic function so it will work with different data types such as number.
In the function we are passing a generic list.We are also returning a list based on the index.So if the index of the list is even then we are including the list element in the returned list.
function GenericFunction<T>(items: T[]): T[] { var combine: T; var lst: T[]=[]; for (var i = 0; i <= items.length; i++) { if(i%2==0) lst.push(items[i]); } return lst; }
We are calling the above function by passing two different types of lists.A list of strings and a list of numbers.
var lettersList = ['a', 'b', 'c', 'd']; var filteredLetters = GenericFunction<string>(lettersList); var numbersList = [1,2,3,4,5,6]; var filteredNumbers = GenericFunction<number>(numbersList);
Leave a Reply