Generics

Generics come in very handy when developing reusable components that can work against any data type. So, the client that consumes this component will decide what type of data it should act upon. Let's create a simple function that returns whatever data is passed to it:

function returnNumberReceived(arg: number): number { 
return arg;
}
function returnStringReceived(arg: string): string {
return arg;
}

As you can see, we need individual methods to process each data type. We can implement the same in a single function using the any data type, as follows:

function returnAnythingReceived (arg: any): any { 
return arg;
}

This is similar to generics. However, we don't have control over the return type. If we pass a number and we can't predict whether the number will be returned or not by the function, The return type can be of any type.

Generics offer a special variable of the T type. Applying this type to the function, as shown, enables the client to pass the data type they would like this function to process:

function returnWhatReceived<T>(arg: T): T { 
return arg;
}

So, the client can call this function for various data types, as shown:

var stringOutput = returnWhatReceived<string>("return this"); // type of output will be 'string' 
var numberOutput = returnWhatReceived<number>(101); // type of output will be number

Note that the data type to be processed is passed by wrapping it in angle brackets (<>) in the function call.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset