November 2018
Beginner
502 pages
10h 22m
English
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:
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 type is generic. In our example, the generic bit is the return type, so we are returning Promise<T>.
If we wanted to use an arrow function, this would be:
const getData = <T>(url: string): Promise<T> => { };
function getData<T>(url: string): ...
Read now
Unlock full access