Generics
Last updated
Was this helpful?
Last updated
Was this helpful?
Generic types are like functions for type declarations the let you pass some arguments (other types) later. This is a (part of) simple linked list implementation:
This code is fine, it works, but gives no type safety:
Generics give us a way to specify: this is a LinkedList
of numbers. Or strings. Or whatever.
This is the same type, but this time written as generic:
T
is the variable type argument here. When creating the head
element we'll specify the type of values in the list:
Trying to give different type of value will result in an error:
Functions can be generic too! First, let's take a look at a simple example:
Great thing about generic functions is that TypeScript is actually quite smart about them. This obviously works as expected:
But TypeScript is also to guess the type T
based on the first argument it gets.
Let's rewrite the add
function from previous example: