Inferring Generics
Explore how TypeScript infers generic types to simplify your code while maintaining type safety. Understand creating and linking generic nodes in linked lists and using generics with classes to enforce consistent types across instances.
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....