Generic Function in TypeScript

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:

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.

We are calling the above function by passing two different types of lists.A list of strings and a list of numbers.

 

You may also like...

Leave a Reply

Your email address will not be published. Required fields are marked *