Generics
As mentioned, generics help us write code that has types that are unknown when writing it but will be known later on, when someone uses the code. They allow us to put "placeholders" where concrete types would've been used otherwise, and for these placeholders to be filled in later, by the user of our code. Generics allow us to write a code once, and use it for multiple types, without losing type-safety along the way, or even increasing the type-safety in comparison to what we can achieve without it.
Let's see how generics help us with typing things more correctly, starting with a very basic function—identity
:
// identity.ts function identity(x: number): number { return x; }
The identity
function takes in a number
, x
, and just returns x
. Now, let's say we want the same functionality for strings too:
// identityString.ts function identityString(x: string) { return x; }
Since type...