Learning generics
Generics allows a type definition to include an associated type that can be chosen by the user of the generic type, instead of being dictated by the type creator. In this way, there are structures and rules, but still some amount of flexibility. Generics will definitely come into play later when we code with React, so let's learn about them here.
Generics can be used for functions, classes, and interfaces. Let's look at an example of generics with functions. Create a file called functionGeneric.ts
and add the following code:
function getLength<T>(arg: T): number { if(arg.hasOwnProperty("length")) { return arg["length"]; } return 0; } console.log(getLength<number>(22)); console.log(getLength("Hello world."));
If we start at the top, we see a function called getLength<T>
. This function...