Inferring Generics
Learn how TypeScript simplifies generic type inference.
We'll cover the following...
TypeScript is always trying to get out of our way. If it can figure out what a generic ought to be, it will relieve us of the responsibility of telling it. Let’s take a look at the following code:
In the code above, we’re able to completely omit telling TypeScript what type T should be. It seems that we’re handing that function call a number, so it’s able to figure out that T is a number in this case.
We can also leverage this to simplify our linked list above:
Let’s explain the code sample above:
Lines 6–8: We define a generic function named
createLinkedListNodethat receive avalueas a parameter, and return the linked list node with thatvalue.Lines 10–12: We create two linked list nodes and name them
firstNodeandsecondNodeby calling thecreateLinkedListNode...