Generics can be applied to a function or a whole class. It's a mechanism for allowing the consumers, own type to be used with the generic function or class. The following sections go through examples of both of these.
Generics
Generic functions
Let's go through an example of a generic function. We are going to create a wrapper function around the fetch JavaScript function for getting data from a web service:
- Let's start by creating the function signature:
function getData<T>(url: string): Promise<T> {
}
We place a T in angled brackets after the function name to denote that it is a generic function. We can actually use any letter, but T is commonly used. We then use T in the signature where the...